Description:
Implement int sqrt(int x).
Compute and return the square root of x.x is guaranteed to be a non-negative integer.
分析:这道题用二分法即可。易出错的地方是数是否越界的处理,我们取high(=x)如果x为INT_MAX的话,在high+low的操作就会造成数字溢出。处理方式见代码
代码:
class Solution {
public:
int mySqrt(int x) {
if(x == 0) return 0;
int low, high, mid;
low = 1;
high = x;
while(low <= high)
{
mid = (high - low) / 2 + low;
if(x / mid < mid)
high = mid - 1;
else if(x / mid > mid)
low = mid + 1;
else
return mid;
}
return high;
}
};【你必须非常努力 才能看起来毫不费力】
508

被折叠的 条评论
为什么被折叠?



