Back to problems

Minimum Operations to Reduce to Zero

Algorithm · Two Sigma · Hard

(This problem is a variant of LeetCode 397. Integer Replacement. Solving that one first is recommended.) You are given a positive integer n. Your goal is to transform it to 0 in the fewest possible moves. In a single move, you may either add or subtract any power of two (e.g., 1, 2, 4, 8, 16, …). The intermediate value is allowed to become negative. Return the minimum number of moves needed to reduce n to 0. Constraints: 1 ≤ n Input: n = 5 Output: 2 Explanation: One optimal…

Checking your access…