You are given a positive integer n. In one operation, you can either add or subtract a power of 2 (e.g., 1, 2, 4, 8, ...) from n. The goal is to find the minimum number of operations to reach zero. This problem is interesting because adding a power of 2 can sometimes reduce the total number of operations by creating a long sequence of 1s in the binary representation that can be cleared with a single subtraction later.
This is a popular question at Uber and Microsoft because it tests Bit Manipulation and Greedy logic. It's similar to how we count change but with the ability to "overpay" and get "change back" (subtraction). It evaluates if you can identify that consecutive 1-bits in binary are more efficiently handled together rather than individually.
The primary pattern is Greedy with Bit Manipulation. Looking at the binary representation of n, if you see a single 1 (like ...010...), it's best to subtract it. If you see two or more consecutive 1s (like ...01110...), it's better to add a power of 2 at the lowest bit's position. This turns the sequence into something like ...10000..., which can then be cleared in one more step. This is essentially the same logic used in Booth's Multiplication Algorithm.
n = 39. Binary: 100111.
111 (three consecutive 1s).39 + 1 = 40. Binary: 101000. (Op 1)40 - 8 = 32. Binary: 100000. (Op 2)32 - 32 = 0. (Op 3)
Total operations = 3.
(Compare to only subtracting: 39 - 32 - 4 - 2 - 1 = 4 operations).A common mistake is using a simple "count set bits" approach, which only works if you are only allowed to subtract. Candidates also sometimes struggle with the logic of when to add vs subtract, failing to see that three or more 1s always benefit from an addition, while two 1s are a tie (it doesn't matter), and one 1 should be subtracted. Another mistake is not handling the "carry" correctly when adding a power of 2.
Practice manipulating integers at the bit level. Specifically, learn how to isolate the lowest set bit (n & -n) and how to clear it (n & (n - 1)). These "bit hacks" are incredibly useful for making your code clean and efficient. Also, try to think about "binary strings" as sequences of clusters, which helps in identifying greedy patterns.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Integer Replacement | Medium | Solve | |
| Minimize XOR | Medium | Solve | |
| Counting Bits | Easy | Solve | |
| Make Array Non-decreasing or Non-increasing | Hard | Solve | |
| Bitwise ORs of Subarrays | Medium | Solve |