Minimum Operations to Reduce an Integer to 0
Real-world version: Gauge Calibration PressesThe statement here is our own: the same inputs, outputs and technique.
A depth gauge reads offset millimetres away from true, and a technician zeroes it with a
calibration dial. One press of the dial shifts the reading by a value that is a power of
two - 1, 2, 4, 8, 16 and upward with no cap - and the same press decides whether that value
is added to the reading or taken off it.
Presses may overshoot: the reading is free to rise past where it started or fall past zero on the way, and nothing forces the reading to shrink at every press. Calibration is finished the moment the reading is exactly 0.
Given offset, return the fewest presses that bring the reading to 0.
Examples
Example 1
- Input
- offset = 23
- Output
- 3
Adding 1 takes the reading to 24, taking off 8 leaves 16, and taking off 16 lands on 0. Each shift is a power of two, so that is three presses.
Example 2
- Input
- offset = 6
- Output
- 2
Taking off 2 leaves 4 and taking off 4 lands on 0, so two presses are enough.
Constraints
- 1 <= offset <= 10^5
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def gauge_presses(offset: int) -> int:public int gaugePresses(int offset)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 2 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's