leetcode题:69. x 的平方根


//69. x 的平方根
//二分法
int mySqrt(int x) {

    if (x <= 1)
        return x;
    int left = 1;
    int right = x;
    int mid = 0;

    while (left < right)
    {
        mid = left + (right - left) / 2;//可防止left + right溢出
        if (mid > x / mid)//即mid*mid > x,防止mid*mid溢出
        {
            right = mid;
        }
        else if (mid < x / mid)//mid*mid < x
        {
            left = mid + 1;
        }
        else
        {
            return mid;
        }
    }

    //精确
    return left - 1;

}

你可能感兴趣的:(leetcode)