69. Sqrt(x) (Divide-and-Conquer)

Implement int sqrt(int x).

Compute and return the square root of x.

注意: 计算平方的时候可能会溢出,所以mid要定义为long

另外,二分法初始上限不可能超过n/2+1

class Solution {
public:
    int mySqrt(int x) {

        int left = 0;
        int right = x/2+1;
        
        while (left <= right)
        {
            long mid = left + (right - left) / 2;
            if (mid * mid <= x && (mid + 1) * (mid + 1) > x)
            {
                return mid;
            }
            else if (mid * mid < x)
                left = mid + 1;
            else
                right = mid - 1;
        }
        
        return -1;
    }
};

 

posted on 2015-10-03 14:25  joannae  阅读(186)  评论(0编辑  收藏  举报

导航