Description
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 ofn. - Change the
ithbit in the binary representation ofnif the(i-1)thbit is set to1and the(i-2)ththrough0thbits 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 2nd operation since the 0th bit is 1. "01" -> "00" with the 1st operation.
Example 2:
Input: n = 6 Output: 4 Explanation: The binary representation of 6 is "110". "110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010" -> "011" with the 1st operation. "011" -> "001" with the 2nd operation since the 0th bit is 1. "001" -> "000" with the 1st operation.
Constraints:
0 <= n <= 109
Solutions
Solution 1: Gray Code Inverse Transform (Gray Code to Binary Code)
This problem essentially asks for the inverse transformation of Gray code at position n, i.e., constructing the original number from the Gray code.
Let's first review how to convert binary code to binary Gray code. The rule is to keep the most significant bit of the binary code as the most significant bit of the Gray code, while the second most significant bit of the Gray code is obtained by XORing the most significant bit and the second most significant bit of the binary code. The remaining bits of the Gray code are computed similarly to the second most significant bit.
Suppose a binary number is represented as Bn-1Bn-2...B2B_1B0, and its Gray code representation is Gn-1Gn-2...G2G_1G0. The most significant bit is kept, so Gn-1 = Bn-1; and for other bits Gi = Bi+1 \oplus Bi, where i=0,1,2..,n-2.
So what is the inverse transformation from Gray code to binary code?
We can observe that the most significant bit of the Gray code is kept, so Bn-1 = Gn-1; and Bn-2 = Gn-2 \oplus Bn-1 = Gn-2 \oplus Gn-1; and for other bits Bi = Gi \oplus Gi+1 … \oplus Gn-1, where i=0,1,2..,n-2. Therefore, we can use the following function rev(x) to obtain its binary code:
int rev(int x) {
int n = 0;
for (; x != 0; x >>= 1) {
n ^= x;
}
return n;
}
The time complexity is O(log n), where n is the integer given in the problem. The space complexity is O(1).
class Solution: def minimumOneBitOperations(self, n: int) -> int: ans = 0 while n: ans ^= n n >>= 1 return ans(code-box)
