LeetCode 69 Sqrt(x) ?
Implement int sqrt(int x).
this is actually need us to find the biggest integer which n^2 < x。
正确答案:
class Solution {//这道题感觉很奇怪
public int mySqrt(int x) {
if (x == 0) {
return 0;
}
int lo = 1;
int hi = x;
while (true) {
int mid = lo + (hi - lo) / 2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
} else if (mid < x / mid) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
}
}
但是仔细观察代码 就会发现这段代码最后没有返回值也能正常的运行,
而且一旦你把while(true)改成while(low<hi)就会被提示没有返回值,这是什么操作?
而且更奇怪的是 如果我们If(mid * mid <= x) 就不行 一定要是if(mid <= x /mid)
所以我特么极度困惑。

浙公网安备 33010602011771号