CodeArchon

mediumBit ManipulationHuluAmazon

Carry-Chain Adder

An ALU designer implements integer addition using only XOR and AND gates (no '+' operator).

Given two integers a and b, return their sum WITHOUT using the operators + and -.

Choose approach

1
0
2
1
Mapstate
a→00000001
b→00000010
carry→00000000
1/2
Narrationstep 1 of 2

a=00000001, b=00000010 → sum-no-carry 00000011, carry 00000000.

1def getSum(a, b):
2 MASK = 0xFFFFFFFF
3 while b & MASK:
4 carry = ((a & b) << 1) & MASK
5 a = (a ^ b) & MASK
6 b = carry
7 return a if a < 0x80000000 else ~(a ^ MASK)
Variables
a=1
b=2
carry=0
nextA=3

How to think about it

  1. Classic half-adder composition.
  2. Terminates once the carry chain exits all bits.

Edge cases to catch in interview

  • Negatives via two's complement.
  • Overflow wraps per fixed word size.

Examples

Example 15
{"a":2,"b":3,"values":[2,3]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed