Minimum Operations to Reduce an Integer to 0

You are given a positive integer n. You can perform the following operation any number of times:

  • Add or subtract a power of 2 from n.

Return the minimum number of operations needed to make n equal to 0.

A number x is a power of 2 if x == 2^i where i >= 0.

Example 1
Inputn = 39
Output3
Adding 1 gives 40, then subtracting 8 gives 32, and subtracting 32 gives 0; it can be shown that 3 operations is the minimum.
Example 2
Inputn = 54
Output3
Adding 2 gives 56, then adding 8 gives 64, and subtracting 64 gives 0, so the minimum number of operations is 3.

Constraints

  • 1 <= n <= 10^5

Asked at 8 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate