69. Sqrt(x)

Posted ArgenBarbie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了69. Sqrt(x)相关的知识,希望对你有一定的参考价值。

Implement int sqrt(int x).

Compute and return the square root of x.

1.

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0 || x == 1)
            return x;
        int l=1, r=x/2+1, m;
        while(l<=r)
        {
            m = (l+r)>>1;
            long long mul = (long long)m*(long long)m;
            if(mul > x)
                r = m-1;
            else if(mul < x)
                l = m+1;
            else
                return m;
        }
        return r;
    }
};

注意:

long long mul = (long long)m*(long long)m;
这一句中,要先将m转换为long long型,再相乘。

 

2. Newton‘s Method

// http://en.wikipedia.org/wiki/Newton%27s_method
int sqrt_nt(int x) {
    if (x == 0) return 0;
    double last = 0;
    double res = 1;
    while (res != last)
    {
        last = res;
        res = (res + x / res) / 2;
    }
    return int(res);
}

 

以上是关于69. Sqrt(x)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode二分 | 牛顿迭代法69_Sqrt(x)

Leetcode 69. Sqrt(x)

69. Sqrt(x)

LeeCode from 0 —— 69. Sqrt(x)

69. Sqrt(x)

69. Sqrt(x)