Leetcode刷题112-69. x的平方根(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/sqrtx/]

1.Question

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.

2.Answer

easy类型题目。。

我的方法1:(逗比解法)
AC代码如下:

class Solution {
public:
    int mySqrt(int x) {
      
        int res = 0;
        
        for(long i = 0; i <= 46340; ++i)  //哈哈哈
        {
            if( i*i == x || (i*i < x && (i+1)*(i+1) > x) )
            {
                res = i;
            }
        }
        return res;
    }
};

我的方法2:(牛顿迭代法)
AC代码如下:

public class Solution {
    public int MySqrt(int x) {
        if(x<2)
            return x;
        double t = x;
        double x0 = x;
        x0 = x0/2 + t/(2*x0);
        while(x0*x0 - t > 0.00001)
            x0 = x0/2 + t/(2*x0);
        return (int)x0;
    }    
}

/*牛顿迭代法
    f(x)=x^2-t
    当f(x)=0时,x就为t的平方根
    取(t,f(t))作为切点,取切线,切线与x轴相交点为x0
    切线方程:y1 - f(x0) = f(x0)'(x1 - x0); 令y1=0
    得:x1 = x0 / 2 + t / (2*x0);
    取(x0,f(x0))作为切点,取切线,切线与x轴相交点为x1
    重复上述操作
    最后切点为(xn,f(xn)),此时f(xn)近似于0,xn为平方根
**/

3.大神解答

速度排名第一(二分查找法)。

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0) return 0;
        long begin = 1;
        long end = INT_MAX;
        long mid;
        
        while(begin + 1 < end) {
            mid = begin + (end - begin)/2;
            if(mid*mid == x) return mid;
            if(mid*mid > x) end = mid;
            else{
                begin = mid;
            }
        }
        if(end*end <= x) return end;
        return begin;
    }
};

4.我的收获

fighting。。。

2019/7/2 胡云层 于南京 112

猜你喜欢

转载自blog.csdn.net/qq_40858438/article/details/94485127