【CSDN Daily Practice】【二分】X的平方根
- 官方思路:经典二分法,
傻白甜
地给了个最大值46340
class Solution {
public int mySqrt(int x) {
int left = 0, right = 46340;
while (left < right) {
int mid = (left + right) / 2;
if (mid * mid < x)
left = mid + 1;
else if (mid * mid > x)
if ((mid - 1) * (mid - 1) <= x)
return mid - 1;
else
right = mid - 1;
else
return mid;
}
if (left * left > x)
return left - 1;
return left;
}
}
public int mySqrt2(int x) {
int k = 0;
int step = x/2;
while (step >= 1) {
while((k+step)*(k+step) <= x){
k += step;
}
step /= 2;
}
return k ;
}