Broken Calculator — LeetCode 991 Python Solution
- Problem
- #991
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- startValue = 2, target = 3
- Output
- 2
- Explanation
- Use double operation and then decrement operation {2 -> 4 -> 3}.
Python solution
class Solution:
def brokenCalc(self, startValue: int, target: int) -> int:
ans = 0
while startValue < target:
if target & 1:
target += 1
else:
target >>= 1
ans += 1
ans += startValue - target
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is \textit{target} |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 991. Broken Calculator is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 991. Broken Calculator?
- LeetCode 991. Broken Calculator is rated Medium on LeetCode.
- What is the time complexity of LeetCode 991. Broken Calculator?
- The Python solution on this page runs in O(\log n), where n is \textit{target}.
- What is the space complexity of LeetCode 991. Broken Calculator?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 991. Broken Calculator cover?
- LeetCode 991. Broken Calculator is tagged Greedy and Math on LeetCode.