Sqrtx

  我只能想出二分的方法,而且还不一定能写出最简洁的代码。无论刷多少遍,牛顿迭代法我都想不到,莫名有种悲哀的感觉:智力是硬伤啊。就算如此,却还要一遍遍不厌其烦地刷,这才是最悲剧的。多说无益,上代码。

  二分:

class Solution {
public:
    int sqrt(int x) {
        if(x==0||x==1)
            return x;

        int left=0;
        int right=x;
        long long mid;
        long long val;
        long long tmp;
        while(left<right){
            mid=(left+right)/2;
            val=mid*mid;
            if(val==x)
                return mid;
            else if(val<x)
                left=mid+1;
            else
                right=mid-1;
        }
        tmp=right*right;
        if(tmp>x)
            return right-1;
        else
            return right;
    }
};

  牛顿迭代法(java):

public class Solution {
    public int sqrt(int x) {  
        if(x < 0) return -1; // assert(x >= 0);  
          
        double n = x;  
        while(Math.abs(n * n - x) > 0.0001){  
            n = (n + x / n) / 2;  
        }  
        return (int)n;  
    }    
}
原文地址:https://www.cnblogs.com/zhizhizhiyuan/p/3949358.html