Java for LeetCode 069 Sqrt(x)

时间:2015-05-16 20:24:52   收藏:0   阅读:170

Implement int sqrt(int x).

Compute and return the square root of x.

解题思路一:

    public int mySqrt(int x) {
        return (int)Math.sqrt(x);
    }

 神奇般的Accepted。

解题思路二:

参考平方根计算方法 计算平方根的算法

这里给出最简单的牛顿法,JAVA实现如下:

    public int mySqrt(int x) {
       	double g = x;
		while (Math.abs(g * g - x) > 0.000001)
			g = (g + x / g) / 2;
		return (int) g;
    }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!