Sum of Two Integers

Add without `+` — XOR is sum without carry; AND-shifted is the carry; loop until carry is zero.

Medium
Time O(log max) Space O(1)
LeetCode
2 min read
bit-manipulation math

Problem#

Return a + b without using + or -.

Examples#

  • a=1, b=23.
  • a=2, b=35; a=-2, b=31.

Constraints#

  • -1000 <= a, b <= 1000.

Approach#

XOR is the bitwise sum (no carry). AND then left-shift by 1 is the carry. Loop: sum = a ^ b; carry = (a & b) << 1; a = sum; b = carry until b == 0. Use unsigned to avoid undefined left-shift on negative.

Solution#

Sum of Two Integers
class Solution {
public:
int getSum(int a, int b) {
unsigned ua = a, ub = b;
while (ub != 0) {
unsigned carry = (ua & ub) << 1;
ua = ua ^ ub;
ub = carry;
}
return (int)ua;
}
};

Editorial#

Two’s complement makes this work uniformly for negative numbers — the overflow at bit 31 naturally implements the negative arithmetic. Using unsigned avoids C++ undefined behavior for left-shifting a 1 into the sign bit.

Complexity#

  • Time: O(log max(|a|, |b|)).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.