Implement int
sqrt(int x).
Compute and return the square root of x.
class Solution {
public:
int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x<=0)
return 0;
if(x==1)
return 1;
int left=1,right=x/2;
int middle=0;
while(left<=right){
middle=((right-left)>>1)+left;
int temp=middle*middle;
if(temp>x || temp/middle!=middle)
right=middle-1;
else if(middle*middle<x && temp/middle==middle)
left=middle+1;
else
return middle;
}
return right;
}
};
本文介绍了一种使用二分查找算法实现整数平方根的方法,并提供了C++代码实现。
295

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



