Blind 75 · #75 · Bit Manipulation

Sum of Two Integers

MediumBitwise additionTime O(32)Space O(1)

Sum of Two Integers is a medium Bit Manipulation problem from the Blind 75. The key pattern is bitwise addition, and a good solution runs in O(32) time.

Problem

Return the sum of two signed 32-bit integers without using addition or subtraction operators.

Examples

Example 1

Input

[-12,7]

Output

-5

Example 2

Input

[1,2]

Output

3

Example 3

Input

[-1,1]

Output

0

Approach

XOR adds without carrying and AND shifted left gives the carry. Repeat until there is no carry left.

PatternBitwise addition
TimeO(32)
SpaceO(1)

Watch out for

Keep values in signed 32-bit range: | 0 in JavaScript, or mask with 0xffffffff in Python and convert back.

More Bit Manipulation problems