Sum of Two Integers

Medium· XOR· arithmetic

Problem

Add two integers without using the + or - operators. Negative inputs must work too, using 32-bit two's complement semantics.

Examples

Input: a = 2, b = 3
Output: 5
Input: a = -2, b = 3
Output: 1

Constraints

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

Hints & approach

Hint 1

Think about how you add binary numbers by hand, column by column.

Hint 2

XOR gives the sum without carries; AND shows where carries happen.

Hint 3

Repeat sum = a ^ b, carry = (a & b) << 1 until the carry is zero.

Approachtry the hints first

a ^ b adds each column while ignoring carries, and (a & b) << 1 is exactly the carry into the next column. Replace a with the partial sum and b with the carry, and loop until no carry remains. In languages with unbounded integers such as Python, mask to 32 bits each step and convert the final result back from two's complement.

Time O(1) — at most 32 iterations · Space O(1)

Output
Call your solution with a test case and Run. For the full judge, submit on LeetCode.