题目
Implement int sqrt(int x).
Compute and return the square root of x.
分析
题目要求实现一个开放函数,返回一个数的开方根
思路
采用二分法。
代码
class Solution {
public:
int mySqrt(int x) {
if(x == 1){
return 1;
}
int start = 0;
int end = x/2;
long int mid = 1;
long int res = 0;
while(start <= end){
mid = start +( end-start)/2;
res = mid*mid;
if(res == x)
return mid;
if(res > x)
end = mid -1;
else
start = mid+1;
}
res = mid*mid;
if(res > x)
mid = mid -1;
return mid;
}
};
注意
1,通过测试,发现,LeetCode的答案其实是向下取整。而通过二分法,可能会计算出向上取整,所以在最后需要在做一下处理,即mid*mid是否大于x,如果大于,则说明向上取整,此时对mid减一即可。即让其向下取整
相关题目
LeetCode : 367. Valid Perfect Square
相关解析见:
http://blog.csdn.net/sjwl2012/article/details/53100695