[LeetCode] Bitwise AND of Numbers Range

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
if(!left or left == right) return left;
int lgl = log2(left), lgr = log2(right);

if(lgl != lgr) return 0;

int res = 0, i = lgl;

while(i >= 0) {
int L = left & (1<<i), R = right & (1<<i);
if(R and !L) return res;
if(L == R) res |= L;
i--;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/09/PS/LeetCode/bitwise-and-of-numbers-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.