码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode 141. x的平方根

时间:2018-01-28 11:16:10      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:code   str   ==   实现   gpo   函数   color   二分   超时   

实现 int sqrt(int x) 函数,计算并返回 x 的平方根。

样例

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

 

解1:二分查找法(超时)

解2:牛顿迭代法

class Solution {
public:
    /*
     * @param x: An integer
     * @return: The sqrt of x
     */
    int sqrt(int x) {
        // write your code here
       if(x==0) return 0;
       double pre=0,res=1;
       while(pre!=res)
       {
           pre=res;
           res=(res+x/res)/2;
       }
       return res;
    }
};

 

LintCode 141. x的平方根

标签:code   str   ==   实现   gpo   函数   color   二分   超时   

原文地址:https://www.cnblogs.com/zslhg903/p/8367926.html

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