[LeetCode] Bitwise AND of Numbers Range

简介: Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.For example, given the range [5, 7], you should return 4.解题

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

For example, given the range [5, 7], you should return 4.

解题思路

① n&(n-1),可以去除n的最低位的1。
② 从n一直与到m,可以去掉的1就是n和m的右端不相等的部分的1。
例如对于如下m和n:
110100111101 –>m
110111111111 –>n
可以去掉的就是n的红色部分的1。

实现代码

//Runtime:100ms
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        char bit = 0;
        while (m != n)
        {
            m >>= 1;
            n >>= 1;
            bit++;
        }

        return m << bit;
    }
};
目录
相关文章
LeetCode 307. Range Sum Query - Mutable
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
77 0
LeetCode 307. Range Sum Query - Mutable
LeetCode 304. Range Sum Query 2D - Immutable
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
79 0
LeetCode 304. Range Sum Query 2D - Immutable
|
索引
LeetCode 303. Range Sum Query - Immutable
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
69 0
LeetCode 303. Range Sum Query - Immutable
LeetCode 201. Bitwise AND of Numbers Range
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
54 0
LeetCode 201. Bitwise AND of Numbers Range