您的位置:首页 > 其它

[LeetCode]69 Sqrt(x)

2015-01-04 11:00 411 查看
https://oj.leetcode.com/problems/sqrtx/
http://blog.csdn.net/linhuanmars/article/details/20089131
public class Solution {
public int sqrt(int x) {

// Assume x >= 0
if (x == 0)
return 0;

return s(x, 0L, (long)x);
}

private int calc(int x, long low, long high)
{
// Why using long.
// is because we might calculate  (MAX_VALUE / 2 + somenumber) ^ 2

if (low > high)
{
// This is the stop point.
return (int)high;
}

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