您的位置:首页 > 其它

[Leetcode]Sqrt(x)

2015-12-02 19:31 381 查看
Sqrt(x)

Total Accepted: 74812 Total Submissions: 310770 Difficulty: Medium

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question

题目很简单,弄清题意。使用二分查找即可,有一点:输入不一定是个完全平方数,如果不是的话取根的下边界整数。

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