Minimum One Bit Operations to Make Integers Zero — Hard Problem & Solution
Two operations transform a binary number: flip the rightmost bit (bit 0); flip bit i + 1 only if bit i is 1 and bits i - 1 … 0 are all 0.
- Difficulty: Hard
- Topics: Math, Dynamic Programming, Bit Manipulation
- Asked at: Amazon, Google, Apple
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Two operations transform a binary number:
- flip the rightmost bit (bit 0);
- flip bit
i + 1only if bitiis1and bitsi - 1 … 0are all0.
Return the minimum number of operations that turns n into 0.
Example 1
Input: n = 3
Output: 2
Explanation: 11 → 01 → 00.
Example 2
Input: n = 6
Output: 4
Explanation: 110 → 010 → 011 → 001 → 000.
Example 3
Input: n = 0
Output: 0
Constraints
0 <= n <= 1000000000
How to solve Minimum One Bit Operations to Make Integers Zero
The two operations are exactly the moves of the standard reflected binary (Gray) code: from a value you may step to the code word before or after it. So the minimum number of operations to reach 0 is the index of n in that code, and the Gray-to-binary conversion computes it directly.
Approach
- Start with
ans = 0. - While
n > 0, XORnintoansand shiftnright by one. - Return
ans.
Why it works
The Gray code of an index i is i ^ (i >> 1), and the inverse is i = g ^ (g >> 1) ^ (g >> 2) ^ … — precisely the running XOR of shifts. Since the operations move one step along the code, the distance from n to the code word 0 is its index.
Complexity
- Time —
O(log n) - Space —
O(1)
Pitfalls
- A breadth-first search over states is exponential and cannot reach
10^9. - The recursive formula
f(n) = 2^k - f(n - 2^(k-1))… is equivalent but far easier to get wrong than the XOR-of-shifts form. - Use an unsigned or arithmetic shift, not a sign-propagating one;
nis non-negative so either works here.
Reference solution
Python
def minimumOneBitOperations(n: int) -> int:
ans = 0
while n > 0:
ans ^= n
n >>= 1
return ansJavaScript
var minimumOneBitOperations = function(n) {
var ans = 0, v = n;
while (v > 0) {
ans ^= v;
v = Math.floor(v / 2);
}
return ans;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.