Cover image for LeetCode Classic 150 Problem P201 Bitwise AND of Numbers Range

LeetCode Classic 150 Problem P201 Bitwise AND of Numbers Range


Timeline

timeline

2025-11-25

init

bit manipulation

Problem:

Find the common binary prefix and then left shift it back.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int rangeBitwiseAnd(int left, int right)
{

int shift = 0;
while (left < right) {
left = left >> 1;
right = right >> 1;
shift++;
}

return right << shift;
}
};