> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Broken Calculator Python Solution with Tests

> Tested Python solution for LeetCode 991 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 991, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Greedy](/catalog/topics/greedy). [View on LeetCode](https://leetcode.com/problems/broken-calculator/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 991   # by problem number
lcpy gen -s broken_calculator   # by problem name
```

## 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.

### Examples

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

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

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

### Constraints

* 1 \<= startValue, target \<= 10^9

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/broken_calculator/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/broken_calculator/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log(target))
    # Space: O(1)
    def broken_calc(self, start_value: int, target: int) -> int:
        ops = 0
        while target > start_value:
            if target % 2:
                target += 1
            else:
                target //= 2
            ops += 1
        return ops + start_value - target
```

## Complexity

| Time | Space |
| - | - |
| O(log(target)) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.