Maximum Number That Makes Result of Bitwise AND Zero - Problem

Given an integer n, return the maximum integer x such that x ≤ n, and the bitwise AND of all the numbers in the range [x, n] is 0.

The bitwise AND operation compares each bit position of two numbers and returns 1 only when both bits are 1, otherwise returns 0.

When we AND all numbers in a range, we need to find the largest starting point where this result becomes 0.

Input & Output

Example 1 — Basic Case
$ Input: n = 5
Output: 0
💡 Note: For x=0, the range [0,5] includes 0&1&2&3&4&5 = 0. Since the range includes 0 and 0 AND anything equals 0, x=0 gives the maximum valid answer.
Example 2 — Single Number
$ Input: n = 1
Output: 0
💡 Note: For x=0, the range [0,1] computes 0&1 = 0. This gives AND result 0, so x=0 is the maximum answer.
Example 3 — Edge Case Zero
$ Input: n = 0
Output: 0
💡 Note: For x=0, the range [0,0] contains only 0, and AND of 0 is 0. So x=0 is the answer.

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Maximum Number That Makes Bitwise AND ZeroGiven n = 5, find maximum x where AND of range [x, n] = 0012345000001010011100101Range [0, 5]0 & 1 & 2 & 3 & 4 & 5 = 0x = 0Maximum x is 0 since range starting from 0 always gives AND = 0
Understanding the Visualization
1
Input
Given integer n = 5
2
Process
Find max x where AND of [x,n] = 0
3
Output
Return x = 0
Key Takeaway
🎯 Key Insight: Since 0 AND any number equals 0, starting from x=0 always produces AND result 0, making it the maximum valid answer
Asked in
Google 15 Microsoft 12 Amazon 8
12.3K Views
Medium Frequency
~15 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen