题目描述
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
思路分析
x的平方根的范围在1~x/2之间,所以我们可以用双指针解题:
- lower = 1;high = x/2; mid = lower + (high - lower) / 2;
- 判断:
mid * mid == x
=>return mid;
mid * mid < x
=>lower = mid + 1;
mid * mid > x
=>high = mid - 1;
- 循环结束条件:
lower > high;
参考代码
public int mySqrt(int x) {
if(x <= 1)return x;
int lower = 1;
int high = x / 2;
while(lower <= high){
int mid = lower + (high - lower) / 2;
if((long) mid * mid == x)return mid;
else if((long) mid * mid < x)lower = mid + 1;
else high= mid - 1;
}
return high;
}
注意:
最后的返回值的确定:当 lower== high == mid 时,无非3种情况:
- mid * mid == x; return high;
- mid * mid < x; lower = mid + 1; 此时 lower > high,返回high;
- mid * mid > x; high = mid - 1; 此时 lower > high,返回high;
因为最后 high <= lower,所以返回high,