Implement int sqrt(int x)
.
Compute and return the square root of x.
中心思想:
二分查找
sqrt(x) < x/2
class Solution {
public:
int mySqrt(int x) {
<span style="white-space:pre"> </span>double begin = 0;
double end = x;
double result = 1;
double mid = 1;
while(abs(result-x) > 0.000001){
mid = (begin+end)/2;
result = mid*mid;
if(result > x) // 二分的范围
end = mid;
else begin = mid;
}
return (int)mid;
}
};