Minimum One Bit Operations to Make Integers Zero Problem
Description
LeetCode Problem 1611.
Given an integer n, you must transform it into 0 using the following operations any number of times:
- Change the rightmost (
0^th) bit in the binary representation ofn. - Change the
i^thbit in the binary representation ofnif the(i-1)^thbit is set to1and the(i-2)^ththrough0^thbits are set to0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2^nd operation since the 0^th bit is 1.
"01" -> "00" with the 1^st operation.
Example 2:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2^nd operation since the 1^st bit is 1 and 0^th through 0^th bits are 0.
"010" -> "011" with the 1^st operation.
"011" -> "001" with the 2^nd operation since the 0^th bit is 1.
"001" -> "000" with the 1^st operation.
Constraints:
0 <= n <= 10^9
Solution
Approach: Gray Code to Binary
The two operations are exactly the moves of the binary reflected Gray code, the sequence where each number differs from the next in one bit: 0, 1, 11, 10, 110, 111, 101, 100, .... In that sequence you go from one code to the next by alternately flipping the lowest bit (operation 1) and flipping the bit just left of the lowest set bit (operation 2). Going backwards uses the same two moves.
From any number there are only these two moves, and the Gray code sequence uses every number exactly once, so the numbers with these moves form one long path through the sequence. The shortest way from n to 0 is to walk back along the path, and the number of steps is the position of n in the Gray code sequence.
The k-th Gray code is k ^ (k >> 1). To go back from a Gray code g to its position k, notice that each bit of k is the XOR of all bits of g at that position and above. So the answer is g ^ (g >> 1) ^ (g >> 2) ^ ..., which a loop computes with ans ^= n; n >>= 1 until n is 0.
Check with example 2: n = 6 = 110. Then 110 ^ 011 ^ 001 = 100 = 4.
Complexity: O(log n) time and O(1) space.
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
# The operations walk the Gray code sequence, so the answer is the position of n in it:
# Gray code -> binary, where each answer bit is the XOR of n's bits at and above it.
ans = 0
while n:
ans ^= n
n >>= 1
return ans