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.
这里使用了牛顿迭代法,记忆一下数学公式,此题还可以用binary search来解决。
Solution 1:
class Solution {
public int mySqrt(int x) {
long res = x;
while (res * res > x) {
res = (res + x / res) / 2;
}
return (int) res;
}
}
Solution2: Binary search
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x;
while (left < right) {
int mid = left + (right - left) / 2;
if (x / mid >= mid) left = mid + 1;
else right = mid;
}
return right - 1;
}
};