您的位置:首页 > 其它

How to compute the square root of an integer?

2013-11-19 03:57 459 查看
This is a binary search problem, but it's very easy to get the wrong answer...

Here is the code I wrote for leetcode testing. There still long way to go to understand this 100%...

public class Solution {
public int sqrt(int x) {
if(x ==0 || x== 1) return x;
if(x < 0) return -1;

long start = 0;
long end = x;

while(end-start >= 0){
long mid = start + (end - start)/2;
long midsqr = mid * mid;

if(midsqr == x)
return (int)mid;
else if(midsqr < x){
start = mid+1;
}
else if(midsqr > x){
end = mid - 1;
}
}
return (int) end;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: