Sum of Two Integers
easy
bit-manipulation
math
Given two integers a and b, return their sum without using the + or - operators. Use bitwise operations (AND, OR, XOR, shifts) to simulate addition with carrying instead.
Input / output
- Input:
a: integer,b: integer - Output:
integer, equal toa + b
Examples
a = 1, b = 2returns3.a = 2, b = 3returns5.a = -2, b = 3returns1.
Constraints
-1,000 <= a, b <= 1,000
Follow-up
Can you explain why a XOR b gives the sum without carries, and (a AND b) << 1 gives exactly the carries that must be added back in, repeating until there is no carry left?
Examples
Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = 2, b = 3
Output: 5
Example 3 (negative operand)
Input: a = -2, b = 3
Output: 1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.