Implement int sqrt(int x)
.
Compute and return the square root of x.
Solution:
Use binary search.
class Solution {
public:
int mySqrt(int x) {
long int left = 0;
long int right = x;
while(left <= right){
long int mid = (left + right) / 2;
if(mid *mid == x){
return mid;
}
if(mid*mid < x){
left = mid + 1;
}else{
right = mid - 1;
}
}
return right;
}
};