← Questions

Fewest powers of two to add or subtract to reach zero

0
UberCodingLast asked Feb 2026

A coding interview question asked in Uber's online assessment, last asked Feb 2026. It tests bit manipulation and greedy.

You get a non-negative integer n. In one operation you may replace n with n + 2^i or n - 2^i for any integer i >= 0. Return the fewest operations that bring n to exactly 0.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • min_operations(n: int) -> int.

Example

min_operations(0)   ->  0
min_operations(1)   ->  1     # 1 - 1
min_operations(7)   ->  2     # 7 + 1 = 8, 8 - 8 = 0
min_operations(39)  ->  3     # 39 + 1 = 40, 40 - 8 = 32, 32 - 32 = 0
min_operations(54)  ->  3     # 54 + 2 = 56, 56 + 8 = 64, 64 - 64 = 0

Constraints

  • 0 <= n <= 10^18.

Clarifying questions

  • Can n go negative during the process? (It never helps.)
  • Is n as large as 10^18, ruling out a search over values?
  • Should I return the operations or only their count?

What a strong answer covers

  • Thinking in binary: an isolated 1 bit costs one subtraction; a run of two or more 1 bits is cheaper to clear by adding at its lowest bit, which turns the run into a single higher bit.
  • A greedy pass from the lowest bit: if n is even, shift right. If n is odd, subtract 1 when the last two bits are 01 or n == 3, and add 1 when they are 11. O(log n) time.
  • Or a memoized recursion f(n) = f(n / 2) for even n and 1 + min(f((n - 1) / 2), f((n + 1) / 2)) for odd n, O(log n) states.
  • Equivalently, the number of non-zero digits in the non-adjacent form of n.
  • Tests: powers of two, 2^k - 1, alternating bits such as 0b10101.

Follow-ups

  • Return the list of operations, not only the count.
  • Prove the greedy rule is optimal.
  • An operation with 2^i now costs i + 1. Does the greedy rule still hold, or do you need a DP over the bits?

Where it's asked

  • Uber · Online assessment · Last asked Feb 202690 min · Two problems on a HackerRank-based platform, camera and screen share on · No AI

What it tests

bit manipulation · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding