Minimum One Bit Operations to Make Integers Zero - Problem
Given an integer n, you must transform it into 0 using the following operations any number of times:
- Change the rightmost (0th) bit in the binary representation of
n. - Change the ith bit in the binary representation of
nif the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Input & Output
Example 1 — Basic Case
$
Input:
n = 3
›
Output:
2
💡 Note:
Binary 3 = 11. First operation: change rightmost bit → 10 (2). Second operation: change bit 1 since bit 0 is 0 → 00 (0). Total: 2 operations.
Example 2 — Single Bit
$
Input:
n = 6
›
Output:
4
💡 Note:
Binary 6 = 110. Following the Gray code pattern: f(6) = 6 ⊕ f(3) = 6 ⊕ 2 = 110 ⊕ 010 = 100 = 4 operations.
Example 3 — Edge Case Zero
$
Input:
n = 0
›
Output:
0
💡 Note:
Already at target 0, no operations needed.
Constraints
- 0 ≤ n ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Integer n in binary representation
2
Operations
Apply allowed bit flip operations
3
Target
Reach 0 with minimum operations
Key Takeaway
🎯 Key Insight: The problem follows Gray code pattern - use formula f(n) = n ⊕ f(n>>1) for O(log n) solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code