Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to emulate 32-bit wrap-around.

Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to emulate 32-bit wrap-around.
def add(a, b):
    M = 0xFFFFFFFF
    while b & M:
        a, b = (a ^ b) & M, ((a & b) << 1) & M
    a &= M
    return a if a <= 0x7FFFFFFF else ~(a ^ M)
print(add(-3, 5), add(-8, -9))
What is printed?
  1. A. 2 -17
  2. B. 2 -15
  3. C. 8 -1
  4. D. -2 -1

Correct answer: A. 2 -17

XOR adds without carries and (a & b) << 1 is the carry; repeating until the carry is 0 gives the sum. Masking to 32 bits stops Python's infinite-precision negatives from looping forever, and ~(a ^ M) converts a 32-bit pattern back to a negative number: 2 and −17.

More Coding Interview Problems questions

Exams that ask this topic