Problem

Minimum Operations to Zero

Learn this problem
SalesforceFULLTIMEOA
See Salesforce hiring insights

Problem statement

You are given an integer n. In one operation, you may add or subtract any power of two from n, such as 2^0, 2^1, 2^2, and so on.

Return the minimum number of operations required to reduce n to 0.

Function

getMinOperations(n: int) → int

Examples

Example 1

n = 21return = 3

One optimal sequence is 21 -> 20 by subtracting 1, 20 -> 16 by subtracting 4, and 16 -> 0 by subtracting 16.

Constraints

  • 1 <= n <= 10^9

More Salesforce problems

drafts saved locally
public int getMinOperations(int n) {
  // write your code here
}
n21
expected3
checking account