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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

## Example

Let us see the following implementation to get better understanding

def solve(n):
n=list(map(int,bin(n)[2:]))
m=[]
last=0
for d in n:
if last==1:
d=1-d
last=d
m.append(d)
m=''.join(map(str,m))
return int(m,2)

n = 6
print(solve(n))

## Input

"95643", "45963"

## Output

4