xinyu04

导航

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.

Solution

暴露循环直接 \(O(n)\). 但是如何找到一种规律呢?

考虑从 \(26\rightarrow 30\):

\[11010\\ 11011\\ 11100\\ 11101\\ 11110 \]

所以只要有一位数不相同,那么直接 \(AND\) 以后就是 \(0.\) 所以我们不断地左移(如果左右端点不相等的话)此时统计个数就是右侧 \(0\) 的个数,然后再将数字右移这些个数即可

点击查看代码
class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        int cnt1=0;
        while(left!=right){
            left>>=1;right>>=1;
            cnt1++;
        }
        return left<<cnt1;
    }
};

posted on 2022-08-15 15:44  Blackzxy  阅读(7)  评论(0编辑  收藏  举报