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: 3
💡 Note: We need to find the maximum x where AND of range [x,5] equals 0. For x=3, we get 3&4&5 = 0&5 = 0 (since 3&4=0). For x=4, we get 4&5=4≠0. So maximum x is 3.
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
Bitwise AND Zero - Maximum X INPUT n = 5 Binary: 5 = 101 Find max x where: AND([x..5]) = 0 0 1 2 3 5 Binary Values: 0: 000 1: 001 2: 010 3: 011 4: 100 5: 101 ALGORITHM STEPS 1 Find MSB Position 5 = 101, MSB at pos 2 2 Pattern Recognition For AND=0, need all bits to cancel at some pos 3 Check Ranges AND([1..5]) = 001 AND 010 AND... != 0 4 Only x=0 Works AND([0..5]) = 0 0 AND anything = 0 AND Calculation: 0: 000 1: 001 2: 010 3: 011 4: 100 5: 101 AND = 000 = 0 FINAL RESULT Maximum x: 0 OK Range [0, 5] gives: AND = 0 Why x=0 is maximum? - x=1: AND([1..5])!=0 - x=2: AND([2..5])!=0 - x=0: AND([0..5])=0 0 is the largest valid x Key Insight: When n is small (like 5), the only way to get AND=0 for range [x,n] is often x=0, because 0 AND anything = 0. For larger n, we use the pattern: x = 2^(floor(log2(n))) makes bits cancel out. TutorialsPoint - Maximum Number That Makes Result of Bitwise AND Zero | Mathematical Pattern Recognition
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