Maximum Number That Makes Result of Bitwise AND Zero - Problem
Given an integer n, find the maximum integer x such that x <= n, and the bitwise AND of all numbers in the range [x, n] equals 0.
The key insight is understanding how bitwise AND behaves across consecutive integers. When you AND consecutive numbers together, bits tend to become 0 as the range increases. Your goal is to find the largest possible starting point where this phenomenon results in a complete zero.
Example: If n = 7, the range [4, 7] gives us 4 & 5 & 6 & 7 = 4 & 5 & 6 & 7 = 4, but [3, 7] gives us 3 & 4 & 5 & 6 & 7 = 0.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 7
โบ
Output:
4
๐ก Note:
Range [4,7]: 4 & 5 & 6 & 7 = 100โ & 101โ & 110โ & 111โ = 100โ & (101โ & 110โ & 111โ) = 100โ & 100โ = 100โ = 4. Wait, let me recalculate: 4&5&6&7 = 4&5 = 4, 4&6 = 4, 4&7 = 4. Actually, we need 4&5&6&7 step by step: 4(100) & 5(101) = 100, then 100 & 6(110) = 100, then 100 & 7(111) = 100 = 4 โ 0. Let's try [3,7]: 3&4&5&6&7. 3(011) & 4(100) = 000 = 0. So x=3 works and gives us 0.
example_2.py โ Power of 2
$
Input:
n = 8
โบ
Output:
0
๐ก Note:
For n=8, we need to find the maximum x where x&(x+1)&...&8 = 0. Since 8 = 1000โ, and we have numbers from 0 to 8, the range [0,8] will definitely include enough bit variations to make the final AND result 0.
example_3.py โ Small Number
$
Input:
n = 3
โบ
Output:
0
๐ก Note:
For n=3: [3,3] = 3 โ 0, [2,3] = 2&3 = 10โ&11โ = 10โ = 2 โ 0, [1,3] = 1&2&3 = 01โ&10โ&11โ = 00โ = 0. But [0,3] = 0&1&2&3 = 0. So maximum x is 0.
Constraints
- 1 โค n โค 109
- The answer will always exist (worst case x = 0)
Visualization
Tap to expand
Understanding the Visualization
1
Understand Bit Patterns
Each integer has a unique bit pattern, consecutive integers differ in specific bit positions
2
AND Behavior
When AND-ing multiple numbers, a bit position becomes 0 if ANY number has 0 in that position
3
Range Analysis
Larger ranges are more likely to have bit variations that result in all positions becoming 0
4
Find Maximum x
We want the largest starting point where the range [x,n] produces AND result of 0
Key Takeaway
๐ฏ Key Insight: The AND of consecutive integers becomes 0 when the range is large enough to include both 0 and 1 values in every bit position. We need to find the maximum starting point where this condition is satisfied.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code