Broken Calculator

Medium · Greedy · Math · Greedy

Problem

A broken calculator shows the integer startValue. Only two keys still work:

Return the minimum number of key presses needed to display target.

Examples

Input: startValue = 3, target = 10
Output: 3

3 → 6 → 5 → 10: double, decrement, double.

Input: startValue = 5, target = 8
Output: 2

5 → 4 → 8: decrement, then double.

Input: startValue = 9, target = 4
Output: 5

Doubling only moves away, so decrement five times.

Constraints

Approaches

Follow-up

What if the calculator could also add 1? Then the reverse moves are halve, add 1 and subtract 1, and the simple parity rule needs one more look ahead: see the use case "Fewest steps down to 1". And if the number of doublings is limited, the same backward greedy spends the doublings where they save the most (the other use case).

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…