Show problems as
Classic problem #2571MediumDynamic ProgrammingGreedyBit Manipulation

Minimum Operations to Reduce an Integer to 0

Real-world version: Gauge Calibration Presses
Tracked in this browser only
Read Minimum Operations to Reduce an Integer to 0 on LeetCode(opens in a new tab)

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

Python
def gauge_presses(offset: int) -> int:
Java
public int gaugePresses(int offset)