Implement int sqrt(int x)
.
Compute and return the square root of x.
二分法还是不熟练啊。
class Solution {
public:
int sqrt(int x) {
if(x == 0) return 0;
if(x < 4) return 1;
long long left = 1;
long long right = x;
long long mid = 0;
long long temp = 0;
while(left < right) {
mid = left + (right - left) / 2;
temp = mid * mid;
if(temp == x) return mid;
if(temp < x) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
temp = right * right;
if(temp > x) {
return right - 1;
}
else {
return right;
}
return 0;
}
};