#991

Broken Calculator

specialist · 780 · lc medium +31 · verified · 55.9% accepted · 2,836 likes · top 49%

Description

A broken calculator currently shows the integer startValue. Each operation either multiplies the displayed number by 2, or subtracts 1 from it.

Given startValue and target, return the fewest operations needed to make the display show target.

Example 1:

Input: startValue = 2, target = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.

Example 2:

Input: startValue = 5, target = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.

Example 3:

Input: startValue = 3, target = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.

Code

1
2
3