69. Sqrt(x)(数学、二分法)

实现针对int类型的sqrt(int x)。计算并返回x的平方根,x确定为非负整数

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

高票做法:
public int sqrt(int x) {
    if (x == 0)
        return 0;
    int left = 1, right = Integer.MAX_VALUE;
    while (true) {
        int mid = left + (right - left)/2;
        if (mid > x/mid) {
            right = mid - 1;
        } else {
            if (mid + 1 > x/(mid + 1))
                return mid;
            left = mid + 1;
        }
    }
}

用了二分法~先找1和最大值之间的中间值,看该值的平方是否大于x。若大于x,则求左段的中间值继续;若小于等于x,则判断该中间值+1是否大约x,若该中间值加1大于x,说明该值为所求值;否则求右段的中间值继续~

原文地址:https://www.cnblogs.com/mafang/p/8675770.html