LeetCode 69. Sqrt(x) x的平方根(Java)

题目:

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:
Input: 4
Output: 2

Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since
the decimal part is truncated, 2 is returned.

解答:

解法一:采用二分法
class Solution {
    public int mySqrt(int x) {
        int start=1;
        int end=x;      
        while(start<=end){
            int middle=(start+end)/2;
            if(middle==x/middle){
                return middle;
            }else if(middle>x/middle){
                end=middle-1;
            }else{
                start=middle+1;
            }
        }
        return end;
    }
}

使用二分法时,要注意middle的平方,会产生溢出。(如首次提交)
LeetCode 69. Sqrt(x) x的平方根(Java)_第1张图片

解法二:采用牛顿迭代法
class Solution {
    public int mySqrt(int x) {
        if(x<=1){
            return x;
        }
        double r=1;
        while(Math.abs(r*r-x)>0.00001){
            r=(r+x/r)/2;
        }
        return (int)r;
    }
}

题目的本质是求平方根,即求解x^2 =t
设一个函数f(x)=x^2- t ,令f(x)=0,则解x就是t的平方根,在图里表示为与X轴的交点横坐标,最终就是要求出这个交点
取图像上一个初始点(X0,f(X0)),作它的切线,切线与X轴交点横坐标为X1,接下来我们又作(X1,f(X1))的切线,最终切线与X轴的交点会无限逼近f(x)=0的交点。
最终得出递推方程:X[i+]=(X[i]+ t/X[i])/2
LeetCode 69. Sqrt(x) x的平方根(Java)_第2张图片

你可能感兴趣的:(LeetCode)