题目介绍
Implement int sqrt(int x).
Compute and return the square root of x.
解决方法
int sqrt(int x) {
if (0 == x) return 0;
int left = 1, right = x, ans;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid <= x / mid) {
left = mid + 1;
ans = mid;
} else {
right = mid - 1;
}
}
return ans;
}
注意:
若判断mid*mid<=x可能会发生溢出,所以使用mid <= x / mid