Minimum Power-of-Two Adjustments
Problem statement
Given a positive integer n, return the minimum number of operations needed to reduce it to zero. In one operation, add or subtract 2^i for any integer i >= 0. Each addition or subtraction costs one operation.
For this exercise, intermediate values are nonnegative and may exceed the starting value. Removing factors of two in an algorithm is a reasoning step, not an allowed free operation on the actual number.
Function
minPowerAdjustments(n: int) → intExamples
Example 1
n = 14return = 2Add 2 to obtain 16, then subtract 16.
Example 2
n = 27return = 3Add 4 to obtain 31, add 1 to obtain 32, then subtract 32.
Example 3
n = 1return = 1Subtract 1 to reach zero.
Constraints
1 <= n <= 65536.- Use integer arithmetic; powers may exceed
n.