Minimum Operations to Reduce an Integer to 0
CodingOASoftware EngineerReported Jan, 2026High Frequency
Examples
Example 1:
Input: n = "5"
Output: 2
Explanation:
Example 2:
Input: n = "21"
Output: 3
Explanation:
Example 1:
Input: n = "5"
Output: 2
Explanation:
Example 2:
Input: n = "21"
Output: 3
Explanation:
You are given a positive integer n. In one operation, you may either add or subtract any power of two.
Return the minimum number of operations required to make n equal to 0.
To preserve the original n < 2^60 bound exactly in this practice environment, n is provided to your function as a base-10 string.
Subtract 1 to get 4, then subtract 4 to reach 0.
One optimal sequence is 21 -> 20 -> 16 -> 0.
n is a valid base-10 representation of an integer1 <= n < 2^60