Bit Manipulation Counting and shifting bits

121. Bitwise AND of Numbers Range

Medium

You are given two integers left and right, with left ≤ right. Return the bitwise AND of every integer from left to right, both ends included.

The bitwise AND of several numbers has a 1 in a binary place only when every one of the numbers has a 1 there. For example, 12 is 1100 and 13 is 1101, so 12 AND 13 is 1100, which is 12.

Example 1

Input: left = 26, right = 30

Output: 24

Explanation: 26 to 30 in binary are 11010, 11011, 11100, 11101 and 11110. Only the top two places are 1 in all five, so the answer is 11000, which is 24. The answer does not have to be one of the numbers.

Example 2

Input: left = 7, right = 8

Output: 0

Explanation: 7 is 0111 and 8 is 1000. No place has a 1 in both, so the answer is 0, even though the range holds only two numbers.

Example 3

Input: left = 2147483646, right = 2147483647

Output: 2147483646

Explanation: These are the two largest values. They differ only in the last place, which is 0 in 2147483646, so the answer is 2147483646.

Check your understanding

Work out the answer for this input before you write any code.

left = 5, right = 7

Constraints

  • 0 ≤ left ≤ right ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.