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
Broken Calculator: Minimum Operations from 2 to 3Start: 2Calculator DisplayOperations:× 2 or - 1Target: 3Goal DisplayAnswer: 2Min OperationsSolution Path243×2-1Step 0Step 1Step 2Total: 2 operations (2 × 2 = 4, then 4 - 1 = 3)
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
Asked in
Google 25 Amazon 20 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen