您的位置:首页 > 其它

LeetCode 69. Sqrt(x),求根算法

2016-03-27 15:28 453 查看
69. Sqrt(x)

Implement 
int sqrt(int x)
.

Compute and return the square root of x.

Subscribe to see which companies asked this question
这道题要找x的平方根,x的平方根肯定小于x/2。要在[1,x/2]有序序列当中找一个数,用二分法:

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