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.
Function Signature
def minimum_one_bit_operations(n: int) -> int:
Rules
-
Bits are numbered from 0 at the least significant end, and "change" means flip the bit (0 becomes 1, 1 becomes 0).
-
For
i = 1
the second operation only requires bit 0 to be
1
, since there are no lower bits.
-
For
n = 0
the answer is
0
.
Constraints
Examples
Input: n = 3
Output: 2
The binary form of 3 is 11. Flip bit 1 (allowed because bit 0 is 1) to get 01, then flip bit 0 to get 00.
Input: n = 6
Output: 4
The steps are 110 -> 010 -> 011 -> 001 -> 000. The first step flips bit 2, which is allowed because bit 1 is 1 and bit 0 is 0.
Input: n = 9
Output: 14
Bit 3 of 1001 can only be flipped once the number reads 1100. Getting from 1001 to 1100 takes 6 operations, flipping bit 3 gives 0100, and clearing 0100 takes 7 more, for 14 in total.