Broken Calculator in Python

PythonServer Side ProgrammingProgramming

Suppose we have a broken calculator that has a number showing on its display, we can perform only two operations −

  • Double − This will multiply the number on the display by 2, or;

  • Decrement − This will decrease the number that is showing, by 1,

Initially, the calculator is displaying the number X. We have to find the minimum number of operations needed to display the number Y.

So if the input is like X = 5 and Y is 8, then the output will be 2, as decrement, it once, then double it

To solve this, we will follow these steps −

  • res := 0

  • while Y > X

    • res := res + Y mod 2 + 1

    • Y := Y / 2 when Y is even, otherwise (Y + 1) / 2

  • return res + X - Y

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def brokenCalc(self, X, Y):
      res = 0
      while Y > X:
         res += Y % 2 + 1
         Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
      return res + X - Y
ob = Solution()
print(ob.brokenCalc(5,8))

Input

5
8

Output

2
raja
Published on 17-Mar-2020 11:10:48
Advertisements