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

Leetcode Sqrt(x)

时间:2014-07-07 14:08:29      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   问题   io   

参考Babylonian method

bubuko.com,布布扣 (x0  越接近S的平方根越好)

bubuko.com,布布扣

bubuko.com,布布扣

class Solution {
public:
    int sqrt(double x) {
        if(x == 0) return 0;
        double root = x/2, tolerance = 1.0e-2;
        do{
            root=(root+x/root)/2;
        }while(abs(root*root-x)>tolerance);
        return root;
    }
};

这题感觉题目有问题,返回的平方根竟然是整数,

另一种方法是是用二分搜索

class Solution {
public:
    int sqrt(int x) {
        if(x < 2) return x;
        int left = 0, right = x;
        while(left <= right){
            int mid = (right+left)/2;
            if(mid < x/mid) left = mid+1;
            else if(x/mid < mid ) right = mid-1;
            else  return mid;
        }
        return right;
    }
};

如果题目要求的时浮点数可以考虑利用浮点数二分搜索

Leetcode Sqrt(x),布布扣,bubuko.com

Leetcode Sqrt(x)

标签:style   blog   http   color   问题   io   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3815322.html

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