Sum of Two Integers

Algorithms
Medium
Google
44.5K views

Calculate the sum of two integers $a$ and $b$, but you are not allowed to use the operators `+` and `-`. Use Bit Manipulation.

Why Interviewers Ask This

Google interviewers ask this to verify your deep understanding of how hardware processes arithmetic at the binary level. They evaluate if you can bypass standard abstractions to solve constraints using bitwise logic, specifically testing your grasp of carry propagation and XOR operations rather than rote memorization of syntax.

How to Answer This Question

1. Clarify Constraints: Immediately confirm that no + or - operators are allowed and discuss handling negative numbers in two's complement representation. 2. Explain Core Logic: State that addition is essentially sum without carry (XOR) plus carry shifted left (AND then shift). 3. Walk Through an Example: Trace a specific case like 5 + 3 (0101 + 0011) step-by-step on a whiteboard, showing intermediate XOR and AND results. 4. Implement Iteratively: Write code using a loop that updates the sum and carry until the carry becomes zero. 5. Analyze Complexity: Briefly mention O(1) time complexity relative to bit width and O(1) space usage, highlighting efficiency.

Key Points to Cover

  • Explicitly state that XOR calculates sum without carry and AND calculates the carry.
  • Demonstrate the iterative loop where carry is shifted left until it vanishes.
  • Correctly handle negative integers using two's complement representation implicitly.
  • Explain the time complexity as proportional to the number of bits, effectively constant for fixed-size integers.
  • Show clear variable tracking during the walkthrough to prove logical flow.

Sample Answer

To solve this without plus or minus, I rely on the fundamental properties of binary addition. Addition consists of two parts: the sum of bits ignoring the carry, and the carry itself which must be added to the next posit…

Common Mistakes to Avoid

  • Attempting to use recursion without checking for stack overflow risks on large inputs.
  • Failing to explain how negative numbers work in two's complement within bitwise operations.
  • Stopping the loop too early before verifying the carry has fully propagated to zero.
  • Confusing the order of operations between calculating the sum and shifting the carry.

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 145 Google questions