您的位置:首页 > 其它

69. Sqrt(x)

2016-07-19 15:46 295 查看
Implement 
int sqrt(int x)
.

Compute and return the square root of x.

暴力法

public static int mySqrt(int x)
{
if(x<=0)
return x;
if(x==1)
return 1;
int i=1;
for(;i<=46340;i++)
if(i*i>x)
break;
return i-1;
}

二分查找

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