Facebook PixelSum of Two Integers — Coding Practice
Sum of Two IntegersMedium

Sum of Two Integers

Medium 5.4k51% acceptance
MathBit Manipulation

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

The challenge is to reconstruct addition from bitwise logic: the XOR of two bits is their sum without carry, and the AND (shifted left by one) is the carry. Keep folding the carry back in until none remains.

Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = 2, b = 3
Output: 5
0b10 XOR 0b11 = 0b01 (sum bits), carry = (0b10 AND 0b11) << 1 = 0b100; folding gives 0b101 = 5.
Example 3
Input: a = -1, b = 1
Output: 0
Two’s-complement bits cancel exactly.
Constraints
  • -1000 ≤ a, b ≤ 1000
  • Do not use the `+` or `-` operators in your logic.
Asked atAmazonGoogleAppleMicrosoft
JavaScript
Loading editor…
Case 1
1, 2
expected: 3
Case 2
2, 3
expected: 5
Case 3
0, 0
expected: 0
Case 4
-1, 1
expected: 0
Case 5
-2, -3
expected: -5
Case 6
100, 250
expected: 350
Case 7
-1000, 1000
expected: 0