您的位置:首页 > 其它

LeetCode:Sqrt(x)

2015-01-07 19:02 281 查看
题目描述:

Implement
int sqrt(int x)
.

Compute and return the square root of x.

思路分析:采用二分查找的思想。当未找到mid=x/mid时,若mid>x/mid,则表示mid-1为平方值最接近但不超过x的值,即结果为mid-1。若mid<x/mid,则表示结果为mid为平方值最接近但不超过x的值,即结果为mid。

代码:

if(x == 0 || x == 1)
return x;
int start = 0;
int end = x;
int result;

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