题目:
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.
思路:
牛顿迭代法,如下图。
代码实现:
class Solution {
public:
int mySqrt(int x) {
if (x == 0){
return 0;
}
double ans = 1;
double pre = 0;
while (abs(ans-pre) >= 1.0){
pre = ans;
ans = (ans + x / ans) / 2;
}
return int(ans);
}
};
discuss:
不同区间对应不同的处理策略。
class Solution {
public:
int mySqrt(int x) {
if (x == 0){
return 0;
}
int left = 1, right = INT_MAX;
while (true){
int mid = left + (right - left) / 2;
if (mid > x / mid){ // x < mid^2
right = mid - 1;
}else if (mid + 1 > x / (mid + 1)){ // x < (mid+1)^2
return mid;
}else{
left = mid + 1;
}
}
}
};