您的位置:首页 > 其它

LeetCode69 Sqrt(x)

2016-09-21 22:56 411 查看
题意:

Implement
int sqrt(int x)
.

Compute and return the square root of x.(Medium)

分析:

二分搜索套路题,不能开方开尽的时候,取结果整数位。

注意:判定条件中,用x / mid == mid而不是 mid * mid == x,否则可能出现int溢出。

代码:

class Solution {
public:
int mySqrt(int x) {
if (x == 0) {
return 0;
}
int start = 0, end = x;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (x / mid == mid) {
return mid;
}
else if (x / mid > mid) {
start = mid;
}
else {
end = mid;
}
}
if (x / end == end) {
return end;
}
return start;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: