Problem · Math

Minimum Operations To Reduce To Zero

Learn this problem
MediumUberOA
See Uber hiring insights

Problem statement

Given a positive integer n, you can either add or subtract 2^i in a single operation where i >= 0. Determine the minimum number of operations required to reduce n to 0.

Find the minimum number of operations required to convert n to 0.

Constraints

  • 1 <= n < 2^40

Function

getMinOperations(n: long) → int

Examples

Example 1

n = 6return = 2

n can be reduced to 0 using two operations:

  • Choose i = 1 and subtract 2^1 from 6, so 6 - 2 = 4.
  • Choose i = 2 and subtract 2^2 from 4, so 4 - 4 = 0.

The answer is 2.

Example 2

n = 21return = 3

One sequence of operations is:

  • Choose i = 0, subtract 2^0 = 1 from 21, converting it to 20.
  • Choose i = 2, subtract 2^2 = 4 from 20, converting it to 16.
  • Choose i = 4, subtract 2^4 = 16 from 16, converting it to 0.

More Uber problems

drafts saved locally
public int getMinOperations(long n) {
  // write your code here
}
n6
expected2
checking account