leetcode 201. 数字范围按位与(Bitwise AND of Numbers Range)

目录

题目描述:

给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。

示例 1:

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

解法:

class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int step = 0;
        while(m != n){
            m >>= 1;
            n >>= 1;
            step++;
            if(m == 0 || n == 0){
                return 0;
            }
        }
        int res = m;
        while(step--){
            res <<= 1;
        }
        return res;
        // 11
        // 00 + 1 = 01
        // get the right-most one: n&(~n + 1)
        // get the left-most one: reset the right-most one, and the recycle
    }
};
上一篇:-bash: /soft/sonar/jdk1.8.0_201/bin/java: /lib/ld-linux.so.2: bad ELF interpreter: No such file


下一篇:[LeetCode 201.] Bitwise AND of Numbers Range