Leetcode 69. x 的平方根 题解

题目链接:https://leetcode-cn.com/problems/sqrtx/
在这里插入图片描述
二分二分,我还是喜欢果断流

代码如下:

class Solution {
public:
    int mySqrt(int x) {
        if(x == 1 || x == 2) {
            return 1;
        }
        int l = 0, r = x / 2;
        while(l <= r) {
            long mid = (l + r) / 2;
            if(mid * mid == long(x)) {
                return mid;
            } else if(mid * mid < long(x)) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
            printf("l = %d, r = %d\n", l, r);
        }
        return r;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42396397/article/details/105921881