Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:二分法。在[0, x/2+1]这个范围内二分就可以。注意要使用long long type,否则当数据过大容易出现溢出。
class Solution {
public:
int sqrt(int x) {
long long start = 0;
long long end = x / 2 + 1;
while (start <= end) {
long long mid = start + (end - start) / 2;
if (x == mid * mid){
return mid;
} else if (x > mid * mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return end;
}
};