Problem: Implement int sqrt(int x)
.
Compute and return the square root of x.
Solution: 二分法思想,要特别注意细节部分,有可能的溢出。
class Solution {
public:
int mySqrt(int x) {
if(x < 0)
return -1;
if(x == 0)
return 0;
if(x == 1)
return 1;
long long left = 0;
long long right = x /2 ;
while(left <= right){
long long int mid = left + (right - left)/2;
long long int val = mid*mid;
if(val == x) return mid;
else if(val < x)
{left = mid + 1;}
else {right = mid -1;}
}
long long tmp = left*left;
if(tmp <= x)
return left;
else
return right;
}
};