Sum of Two Integers
Examples
Example 1:
Input: a = 1, b = 1
Output: 2
Example 2:
Input: a = 4, b = 7
Output: 11
Example 1:
Input: a = 1, b = 1
Output: 2
Example 2:
Input: a = 4, b = 7
Output: 11
Given two integers a and b, return the sum of the two integers without using the + and - operators.
-1000 <= a, b <= 1000Use bitwise operations to simulate addition. a ^ b computes sum without carry, and (a & b) << 1 computes carry. Repeat until there is no carry. Use a 32-bit mask to handle negatives.
Binary addition is equivalent to repeated computation of partial sums and carries. Iterating until carry is zero yields the exact sum. The mask keeps results within 32-bit two's complement, matching typical integer behavior.
O(1) (bounded by word size)O(1)class Solution:
def getSum(self, a: int, b: int) -> int:
MASK = 0xFFFFFFFF
MAX_INT = 0x7FFFFFFF
while b != 0:
a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
return a if a <= MAX_INT else ~(a ^ MASK)