Add Without Plus Operator

Medium~20 min

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

The key idea: XOR gives the sum without carrying, and AND followed by a left shift gives the carry. Repeat until there is no carry left.

Note: Your solution should handle negative numbers correctly.

Examples

Example 1
Input: a = 1, b = 2
Output: 3
Explanation: 1 + 2 = 3. XOR: 1 ^ 2 = 3, carry: (1 & 2) << 1 = 0. No carry, so result is 3.
Example 2
Input: a = 5, b = 3
Output: 8
Explanation: 5 + 3 = 8. XOR gives partial sum, carry propagation finishes in a few iterations.
Example 3
Input: a = -1, b = 1
Output: 0
Explanation: -1 + 1 = 0.

Constraints

  • -1000 <= a, b <= 1000
  • Do not use + or - operators
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run