码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 069 Sqrt(x)

时间:2015-05-16 20:24:52      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

 

Java for LeetCode 069 Sqrt(x)

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4508453.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!