您的位置:首页 > 其它

二分查找——sqrtx

2016-05-28 15:53 465 查看

题目描述

Implementint sqrt(int x).

Compute and return the square root ofx.

public class Solution {
public int sqrt(int x) {
if(x <= 0)
return 0;
int start=1;
int end=x/2+1;//end*end=x*x/4+x+1>x,提快速度;
while(start<end-1)
{
int mid=start+(end-start)/2;
if(mid == x/mid)//若用mid*mid 会越界。
return mid;
else if(mid > x/mid)
end=mid;
else
start=mid;
}
return start;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: