您的位置:首页 > 其它

[LeetCode] Sqrt(x)

2015-08-22 22:27 369 查看
Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

题目的意思是找x的平方根,思路也是比较简单 是使用二分法查找

关键在比较时有个问题不能使用mid*mid与x比较,因为可能溢出

而是应该使用mid与x/mid

class Solution {
public:
int mySqrt(int x) {
if(x==0||x==1)  return x;
int left = 1;
int right = x/2+1;
int mid;
while(1){
//mid = (right + left)/2;
mid = left + (right - left)/2;          //to prevent overflow
if(mid> x/mid)
right = mid-1;
else if(mid + 1 > x/(mid + 1))
return mid;
else
left = mid+1;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: