sqrt(x)

题目:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example:

Input: 4
Output: 2
Example 2:

Input: 8
Output: 2

Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

答案:

class Solution {
    public int mySqrt(int x) {
        long xi = x;
        while(xi * xi > x) {
            xi = (xi + x/xi)/2;
        }
        return (int)xi;
    }
}


binary search的解法要注意m*m有可能会overflow,所以要用long变量

class Solution {
public int mySqrt(int x) {
long l = 0, r = (int)Math.ceil(x / 2.0);
while(l <= r) {
long m = l + (r - l) / 2;
if(m * m == x || (m*m < x && (m+1) * (m+1) > x)) {
return (int)m;
}
else if(m * m < x) {
l = m + 1;
}
else {
r = m;
}
}
return 0;
}
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 实在忙不过来,只能写文字最少的文章,告诉你们我的理财产品好了,不是股票,而是基金,基金名字叫“嘉实全球互联网股票...
    新菜日记阅读 400评论 3 1
  • 目标: 籍由我通过运用业力种子法则,愿我顺利实现目标:在十月份和我的太太恢复初恋时的状态,彼此恩爱,给我们的孩子一...
    无限可能ken阅读 79评论 0 0