← Questions
Fewest powers of two to add or subtract to reach zero
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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
ngo negative during the process? (It never helps.) - Is
nas 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
nis even, shift right. Ifnis odd, subtract 1 when the last two bits are01orn == 3, and add 1 when they are11. O(log n) time. - Or a memoized recursion
f(n) = f(n / 2)for evennand1 + min(f((n - 1) / 2), f((n + 1) / 2))for oddn, 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 as0b10101.
Follow-ups
- Return the list of operations, not only the count.
- Prove the greedy rule is optimal.
- An operation with
2^inow costsi + 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
