Broken Calculator - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
startValue = 2, target = 3
›
Output:
2
💡 Note:
Use operations: 2 × 2 = 4, then 4 - 1 = 3. Total: 2 operations
Example 2 — Target Smaller
$
Input:
startValue = 5, target = 8
›
Output:
2
💡 Note:
Use operations: 5 - 1 = 4, then 4 × 2 = 8. Total: 2 operations
Example 3 — Only Subtraction
$
Input:
startValue = 3, target = 10
›
Output:
3
💡 Note:
Working backwards: 10÷2=5, 5+1=6, 6÷2=3. Total: 3 operations
Constraints
- 1 ≤ startValue, target ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
startValue=2, target=3, operations: ×2, -1
2
Process
Find minimum operations to reach target
3
Output
2 operations needed
Key Takeaway
🎯 Key Insight: Working backwards from target with reverse operations is more efficient than exploring all forward paths
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code