Implement int sqrt(int x)
.
Compute and return the square root of x.
可以用binary search,适合用upperbound的模板, 模板:Binary Search - 二分搜索。因为num除了0、1外,sqrt的结果都会<=num/2,这样把start设成0,end设成n/2+2,条件设成mid>x/mid。注意这里不要用mid*mid>x,因为mid*mid会溢出。代码如下:public class Solution {
public int mySqrt(int x) {
int start = 0, end = x / 2 + 2;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
//don't use mid*mid > x, it will overflow
if (mid > x / mid) {
end = mid;
} else {
start = mid;
}
}
return end - 1;
}
}