首页 > 其他 > 详细

LeetCode OJ:Sqrt(x)

时间:2014-01-28 23:59:04      阅读:517      评论:0      收藏:0      [点我收藏+]

Sqrt(x)

 

Implement int sqrt(int x).

Compute and return the square root of x.

算法思想:

1、二分法

class Solution {
public:
    int sqrt(int x) {
        if(x < 0) return -1;
        
        long long target = (long long)x;  
        long long left = 0;
        long long right = target;
        long long mid;
          
        while(left <= right){
            mid = left + (right - left) / 2;  
            
            if(mid * mid == target || (mid * mid < target && (mid + 1) * (mid + 1) > target)){  
               return (int)mid;  
            } else if(mid * mid < target){  
                left = mid + 1;  
            } else{  
                right = mid - 1;  
            }  
        }  
    }  
};

answer2:牛顿迭代

class Solution {
public:
    int sqrt(int x) {
        if(x < 0) return -1;
        
        double n=x;
        while(abs(n*n-x)>0.0001)n=(n+x/n)/2;
        
        return (int)n;
    }  
};


LeetCode OJ:Sqrt(x)

原文:http://blog.csdn.net/starcuan/article/details/18843641

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