FastPrepMinimum Power-of-Two Adjustments

Minimum Power-of-Two Adjustments

NVIDIA logoNVIDIA● MediumFULLTIMEOA
Learn

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) → int

Examples

Example 1

n = 14return = 2

Add 2 to obtain 16, then subtract 16.

Example 2

n = 27return = 3

Add 4 to obtain 31, add 1 to obtain 32, then subtract 32.

Example 3

n = 1return = 1

Subtract 1 to reach zero.

Constraints

  • 1 <= n <= 65536.
  • Use integer arithmetic; powers may exceed n.

More NVIDIA problems

See NVIDIA hiring insights
public int minPowerAdjustments(int n) {
    // Write your code here
}
n14
expected2
Checking account…