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
Solution 1: Binary search
Consideration
- Make two boundary low and high. Initially, let low be 1 and high be num x.
- while low <= high, we check if the middle value (mid = low +(high-low)/2) is larger than x divide by mid. If yes, we decrease high by 1. Otherwise, we increase low by 1.
- return high.
Time Complexity: O(logn)
class Solution {
public int mySqrt(int x) {
int l = 1;
int r = x;
while (l <= r) {
int m = l + (r - l) / 2;
if (m > x / m) {
r = m - 1;
} else {
l = m + 1;
}
}
return r;
}
}
Solution 2: Newton’s method
Consideration
- After the math calculation, the wanted root’s value is res[i+1] = (res[i] + x/res[i])/2.
- The result is the one that makes current result == previous result.
class Solution {
public int mySqrt(int x) {
if(x == 0)
return x;
double last = 0;
double res = 1;
while(last != res){
last = res;
res = (res + x/res)/2;
}
return (int)res;
}
}
References