Problem
Implement int sqrt(int x).
Compute and return the square root of $x$, where $x$ is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
1 | |
Example 2:
1 | |
Explanation 1
- We can use binary search method to solve this problem. Left is 1, and right is the square root of the Integer.MAX_VALUE.
midis our guess number.
Solution 1
1 | |
Explanation 2
-
Observe the square of the number: 1, 4, 9, 16, 25, 36, and observe their difference (
add): 3, 5, 7, 9, 11. We notice that the difference is adding 2 each time. In other word, the value ofaddis plus 2 each time, and we can compare (sum += add with target), 1 + 3 = 4, 4 + 5 = 9, 9 + 7 = 16, 16 + 9 = 25, 25 + 11 = 36. -
So, we can initialize the sum = 0, add = 1, counter (or res) = 0, the next iteration, sum += add = 1, add = 3, counter = 1, in other word, when sum = 1, counter = 1, when sum = 4, counter = 2, and we compare the sum with target.
-
Special case is the
sum + add > MAX_VALUEso, we useMAX_VALUE - sum < addto avoid overflow.
Solution 2
1 | |