您的位置:首页 > 其它

Leetcode: Sqrt(x)

2014-09-17 13:24 351 查看
Implement 
int sqrt(int x)
.

Compute and return the square root of x.

思路:二分法。在[0, x/2+1]这个范围内二分就可以。注意要使用long long type,否则当数据过大容易出现溢出。

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