Program to find minimum one bit operations to make integers zero in Python

Suppose we have a number n, we have to transform it into 0 using the following operations any number of times −

  • Select the rightmost bit in the binary representation of n.

  • Change the ith bit in the binary representation of n when the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.

So finally we have to find the minimum number of operations required to transform n into 0.

So, if the input is like n = 6, then the output will be 4 because initially 6 = "110", then convert it to "010" by second operation, then convert to "011" using first operation, then convert to "001" using second operation and finally convert to "000" using first operation.

To solve this, we will follow these steps −

  • n := list of binary bits of number n

  • m:= a new list

  • last:= 0

  • for each d in n, do

    • if last is same as 1, then

      • d:= 1-d

    • last:= d

    • insert d at the end of m

  • m:= make binary number by joining elements of m

  • return m in decimal form


Let us see the following implementation to get better understanding

def solve(n):
   for d in n:
      if last==1:
   return int(m,2)

n = 6


"95643", "45963"