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 n if 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
Minimum Bit Operations: Transform n=3 to 011 (3)Initialflip bit 010 (2)After op 1flip bit 100 (0)TargetOperation Rules:1. Can always flip rightmost bit (bit 0)2. Can flip bit i if bit i-1 is 1 and bits 0 to i-2 are all 0Minimum Operations: 2
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
Asked in
Google 35 Facebook 28 Microsoft 22
32.4K Views
Medium Frequency
~35 min Avg. Time
847 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