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 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

Let us see the following implementation to get better understanding −

class Solution(object):
   def brokenCalc(self, X, Y):
      """
      :type X: int
      :type Y: int
      :rtype: int
      """
      res = 0
      while Y > X:
         res += Y % 2 + 1
         Y = Y // 2 if Y % 2 == 0 else (Y + 1)//2
      return res + X - Y

Input

5
8

Output

2
raja
Published on 17-Mar-2020 06:40:48
Advertisements