Leetcode: Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

这类问题基本是二分,需要考虑溢出的情况。

class Solution {
public:
    int sqrt(int x) {
        assert(x >= 0);
        if (x <= 1) {
            return x;
        }
        
        uint low = 1;
        uint up = (x > 0xFFFF ? 0xFFFF : x);
        uint mid;
        uint multi;
        while (low <= up) {
            mid = low + (up - low) / 2;
            multi = mid * mid;
            if (multi == x) {
                return mid;
            }
            else if (multi < x) {
                low = mid + 1;
            }
            else {
                up = mid - 1;
            }
        }
        
        return (low - 1);
    }
};

======================第二次=======================

还是溢出 - 当我们取最大值为0xFFFF时,平方就会溢出。2^31 - 1的平方根小于0xFFFF,但不能直观的找到,所以简单一点选择0xFFFF。

class Solution {
public:
    int sqrt(int x) {
        if (x <= 0) {
            return 0;
        }
        
        int low = 1;
        int up = x > 0xFFFF ? 0xFFFF : x;
        int mid;
        uint result;
        while (low <= up) {
            mid = low + (up - low) / 2;
            result = mid * mid;
            if (result == x) {
                return mid;
            }
            else if (result < x) {
                low = mid + 1;
            }
            else {
                up = mid - 1;
            }
        }
        
        return up;
    }
};


你可能感兴趣的:(LeetCode,二分查找)