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 One Bit Operations to Make Integers Zero INPUT n = 3 Binary Representation 1 bit 1 1 bit 0 Gray Code Sequence 0: 00 (0) 1: 01 (1) 2: 11 (3) <-- n 3: 10 (2) 4: 110 (6) ... ALGORITHM STEPS 1 Recognize Pattern n appears at position in Gray code sequence 2 Gray to Binary Position = Gray^(-1)(n) Use XOR operations 3 Calculate Position For n=3 (binary 11): 3 XOR 1 = 2 4 Return Position Position in sequence = min operations f(n) = n XOR f(n>>1) f(3) = 3 XOR f(1) f(3) = 3 XOR 1 = 2 FINAL RESULT Operations Trace Start: 11 (3) Initial state Op 1 Step: 10 (2) Change bit 0 Op 2 End: 00 (0) Change bit 1 Output 2 Key Insight: The minimum operations to reach 0 equals the position of n in the Gray code sequence. Gray code position can be computed by: result = n; while(n > 0) { n >>= 1; result ^= n; } TutorialsPoint - Minimum One Bit Operations to Make Integers Zero | Gray Code Pattern Recognition
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