LeetCode 201 数字范围按位与

LeetCode 201 数字范围按位与

问题描述:
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含m, n两端点)。
寻找公共前缀
两数a,b相与的结果等于保留a,b最长公共前缀,并将其它部分全部置为0

执行用时:6 ms, 在所有 Java 提交中击败了99.82%的用户
内存消耗:39 MB, 在所有 Java 提交中击败了73.58%的用户

class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int shift = 0;
        // 找到公共前缀
        while (m < n) {
            m >>= 1;
            n >>= 1;
            ++shift;
        }
        return m << shift;
    }
}

原文地址:https://www.cnblogs.com/CodeSPA/p/13549718.html