Minimum Operations to Reduce an Integer to Zero
Problem statement
Given a positive integer n, return the minimum number of operations needed to reduce it to zero.
In one operation, you may add or subtract 2^b for any nonnegative integer b. Intermediate values may be larger than the starting value. Count only these additions and subtractions; rewriting a number in binary is not an operation.
Function
minOperations(n: int) → intExamples
Example 1
n = 39return = 3One optimal sequence is 39 - 32 = 7, 7 + 1 = 8, then 8 - 8 = 0, using 3 operations.
Example 2
n = 54return = 3Use 54 + 2 = 56, 56 + 8 = 64, then 64 - 64 = 0.
Example 3
n = 8return = 1Subtract 2^3 = 8 once.
Constraints
- For this exercise, assume
1 <= n <= 10^5. - Each operation adds or subtracts one power of two.