[LeetCode] 201. Bitwise AND of Numbers Range

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

Example 1:
Input: left = 5, right = 7
Output: 4

Example 2:
Input: left = 0, right = 0
Output: 0

Example 3:
Input: left = 1, right = 2147483647
Output: 0

Constraints:
0 <= left <= right <= 231 - 1

数字范围按位与。

给你两个整数 left 和 right ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 left 、right 端点)。

思路

题意是给一个范围 [m, n],输出这个范围内所有二进制数做 AND 操作之后的结果。思路是位运算。举个例子,如下是四个连续的数字,

0100010
0100011
0100100
0100101

注意,当他们被AND的时候,会发现最低位会变成0。因为两个相邻的数字的最低位一定不一样,所以AND之后的结果只会是0。这样不停地AND之后(同时向右移,假设最后右移了 X 次),到这一步发现前面若干位都是一样的时候,就可以停止了。最后将 m 向左移动 X 次,就会得到最后的结果。

0100xxx
0100xxx
0100xxx
0100xxx

复杂度

时间O(1) - 只要跑32次
空间O(1)

代码

Java实现

class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int offset = 0;
        while (m != n) {
            m >>= 1;
            n >>= 1;
            offset++;
        }
        return m << offset;
    }
}

JavaScript实现

/**
 * @param {number} m
 * @param {number} n
 * @return {number}
 */
var rangeBitwiseAnd = function(m, n) {
    let offset = 0;
    while (m !== n) {
        m >>= 1;
        n >>= 1;
        offset++;
    }
    return m << offset;
};
posted @ 2020-03-25 13:26  CNoodle  阅读(143)  评论(0编辑  收藏  举报