Was it helpful?

Question

Program to find minimum number of operations required to make one number to another in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number start and another number end (start < end), we have to find the minimum number of operations required to convert start to end using these operations −

  • Increment by 1
  • Multiply by 2

So, if the input is like start = 5, end = 11, then the output will be 2, as we can multiply 2 to get 10, then add 1 to get 11.

To solve this, we will follow these steps −

  • ct:= 0
  • while end/2 >= start, do
    • if end mod 2 is same as 1, then
      • end := end - 1
      • end := end/2
      • ct := ct + 2
    • otherwise,
      • end:= end/2
      • ct := ct + 1
  • ct := ct +(end-start)
  • return ct

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, start, end):
      ct=0
      while(end/2>=start):
         if end%2==1:
            end-=1
            end=end/2
            ct+=2
         else:
            end=end/2
            ct+=1
      ct+=(end-start)
      return ct
ob = Solution()
print(ob.solve(5,11))

Input

5,11

Output

2
raja
Published on 05-Oct-2020 11:01:00
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top