首页 > 其他 > 详细

LeetCode——Sqrt(x)

时间:2015-06-29 06:16:27      阅读:264      评论:0      收藏:0      [点我收藏+]

Description:

Implement int sqrt(int x).

Compute and return the square root of x.

 好好学习数学还是非常有用的,牛顿迭代法 求解。

    计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示。

   首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1

   同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2

   以此类推。

   以这样的方式得到的xi会无限趋近于f(x)=0的解。

   判断xi是否是f(x)=0的解有两种方法:

   一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。

 

public class Solution {
    public int mySqrt(int x) {
        if (x ==0)  
           return 0;  
        double pre;  
        double cur = 1;  
        do  
        {  
            pre = cur;  
            cur = x / (2 * pre) + pre / 2.0;  
        } while (Math.abs(cur - pre) > 0.00001);  
        return (int) cur;  

        
    }
}

 

 

 

LeetCode——Sqrt(x)

原文:http://www.cnblogs.com/wxisme/p/4606423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!