Fewest Add-or-Subtract Power-of-Two Steps to Reduce n to Zero
Company: Salesforce
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Online Assessment
Overview: An integer problem: reduce a positive n to zero with the fewest operations, where each operation adds or subtracts a power of two. It tests reasoning about binary representations, proving a strategy optimal, and working safely with integers larger than 32 bits.
Read the full Salesforce Software Engineer interview experience this question came from
Constraints
- 1 <= n <= 9007199254740991 (2^53 - 1); the original assessment allowed n up to 2^60 - 1, and this version caps n so every supported language represents it exactly
- n can exceed 2^31 - 1: use 64-bit integers (long in Java, long long in C++) or arbitrary precision
- Each operation adds or subtracts 2^i for any integer i >= 0; powers may repeat and intermediate values are unrestricted
- Return the minimum operation count, a positive integer uniquely determined by n
Examples
Input: (7,)
Expected Output: 2
Input: (45,)
Expected Output: 4
Hints
- Look at n in binary. What does adding 1 do to a block of consecutive trailing ones?
- Process bits from least significant to most significant. When the lowest set bit is isolated, removing it directly is never worse; when it starts a run of two or more ones, a carry can replace the whole run.
- After handling the lowest bit, the value is even, so you can shift right and repeat. The whole algorithm takes one pass over the bits.