69. Sqrt(x)

问题描述

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.

解法

1、无脑循环
2、二分查找 O(logn)
3、牛顿迭代法


69. Sqrt(x)_第1张图片
image.png
class Solution {
public:
    int mySqrt(int x) {
        if (x < 2) return x;
        for(long long i = 0; i <= x; i++) {
            if (i * i > x) return i - 1;
        }
        return -1;
    }
};

class Solution {
public:
    int mySqrt(int x) {
        if (x < 2) return x;
        int l = 1;
        int r = x / 2;
        while(l < r) {
            long long m = l + (r - l)/2;
            if (m * m > x) {
                r = m - 1;
            } else {
                if ((m + 1) * (m + 1) > x) return m;
                l = m + 1;
            }
        }
        return l;
    }
};
//不用long类型的
public int mySqrt(int x) {
    int left = 1, right = x;            
    while(left<=right) {
        int mid = left + (right-left)/2;// 不能使用(right+left),因为有可能整数溢出
        if(mid <= x/mid) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return left-1;
}

class Solution {
public:
    int mySqrt(int x) {
        if (x < 2) return x;
        long i = x;
        while (i * i > x){
            i = (i + x / i) / 2;
        }
        return i;
    }
};

你可能感兴趣的:(69. Sqrt(x))