Mid/SeniorGreedyMath

Broken Calculator

There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:

  • Multiply the number on display by 2, or
  • Subtract 1 from the number on display.

Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.

Example 1
InputstartValue = 2, target = 3
Output2
Use double operation and then decrement operation {2 -> 4 -> 3}.
Example 2
InputstartValue = 5, target = 8
Output2
Use decrement and then double {5 -> 4 -> 8}.

Constraints

  • 1 <= startValue, target <= 10^9

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate