刚开始写的:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
int l = 0, r = x;
while (l < r)
{
int mid = l + (r - l) / 2 + 1;
if (mid * mid > x) r = mid - 1;
else l = mid;
}
return l;
}
};
结果爆int了。
改成这样:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
int l = 0, r = x;
while (l < r)
{
int mid = l + (r - l) / 2 + 1;
if ((long long)mid * mid > x) r = mid - 1;
else l = mid;
}
return l;
}
};
就通过了。
附上分析过程:
标签:return,int,Solution,mid,long,else,69,平方根 From: https://www.cnblogs.com/hisun9/p/18522430