【Math】数学类问题集合

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.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

实现输入为非负整数的Sqrt(x)函数。若sqrt(x)不为整数,输出向下取整。

使用二分法实现。 使用二分法,则循环的终止条件为:

1,找到了合适的值

2,越过了边界条件(两端互相越过,l<=r)

    int mySqrt(int x) {
        if(x==0 || x==1) 
            return x;
        
        // 定义左右边界
        int l = 1, r = x, res;
        
        // 当两端未相遇时,不断使用二分
        while(l <= r){
            // 首先得到二分点
            int m = l + (r - l)/2;
            // m==x/m。 即得到了需要的答案m
            if(m == x / m)
                return m;
            // m取大了,右边界左移
            else if(m > x / m)
                r = m - 1;
            // m取小了,左边界右移。同时保留一个记忆res。因为可能正确的根是含小数的,等于是记住整数部分
            else{
                l = m + 1;
                res = m;
            }
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/weixin_38628152/article/details/82970330