# Program to find number of given operations required to reach Target 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 two values start and end, we have to find the minimum number of operations needed to convert start to end by using these operations −

• Decrement by 1

• Multiply by 2

So, if the input is like start = 2, end = 7, then the output will be 3, as we can multiply 2 to get 4, then multiply 2 to get 8 and then subtract 1 to get 7.

To solve this, we will follow these steps −

• ans := 0

• Do the following infinitely, do

• if end <= start, then

• return ans + start − end

• otherwise when end is odd, then

• end := end + 1, ans := ans + 1

• otherwise,

• end := quotient of end / 2

• ans := ans + 1

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, start, end):
ans = 0
while True:
if end <= start:
return ans + start - end
elif end % 2:
end += 1
ans += 1
else:
end //= 2
ans += 1
ob1 = Solution()
start = 2
end = 7
print(ob1.solve(start, end))

## Input

2, 7

## Output

3
Updated on 21-Oct-2020 11:57:08