1. 程式人生 > >LeetCode 69. Sqrt(x)

LeetCode 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.

/**
 * 使用二分查詢法
 * 任何一個數的算術平方根絕對不會大於這個數的的一半(顯然)
 * 所以二分查詢初始設為left=1,right=x/2
 * 退出條件為:mid*mid<=x && (mid+1)*(mid+1)>x
 */
public class SqrtSolution {
    public int mySqrt(int x) {
        int left = 1;
        int right = x / 2;
        while (right >= left) {
            int mid = (left + right) / 2;
            //乘法變為除法,防止溢位
            if (mid > x / mid) {
                right = mid - 1;
            } else if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
                return mid;

            } else {
                left = mid + 1;
            }
        }

        return x;
    }
}