Intermediate Level

Implement the bitwiseAndRange method that returns the bitwise AND of all numbers in the given range.

The input contains two integers left and right, representing an inclusive range.

Your task is to return the bitwise AND of every integer from left to right.

For example, the bitwise AND of 5, 6, 7 is 4, so input 5|7 returns 4.

Example 1

Input
left (int) = 5
right (int) = 7
Returns (int) 4

Example 2

Input
left (int) = 0
right (int) = 0
Returns (int) 0

Example 3

Input
left (int) = 1
right (int) = 2147483647
Returns (int) 0

The result keeps only the common binary prefix shared by all numbers in the range.

When left and right are different, remove their last binary bit by shifting both numbers right. Count how many shifts were done. Once both numbers become equal, that common value is the shared prefix.

Shift the common prefix back to the left by the same count to get the final result.

Pseudocode:

function bitwiseAndRange(left, right):
    shifts = 0
    while left != right:
        left = left / 2
        right = right / 2
        shifts++
    return left * powerOfTwo(shifts)
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.