Return the sum of two integers a and b, without using the + or - operators anywhere in your code (that includes +=, -=, ++ and --). Bitwise operators such as &, |, ^, ~ and the shifts are all allowed.
The judge only sees your answer, so it can't check which operators you used. The puzzle is how to add with bits alone.
Example 1
Input: a = 9, b = 6
Output: 15
Example 2
Input: a = -7, b = 4
Output: -3
One value is negative, so the sum falls below zero.
Example 3
Input: a = -12, b = -30
Output: -42
Constraints
-1000 <= a, b <= 1000Add in binary, column by column. a ^ b gives each column's digit if you ignore carries, and a & b marks the columns that produce a carry.
Without +, fall back on how you add on paper, but in base 2. Line the two numbers up, go column by column from the right, and in each column add two digits plus whatever carry came in. In binary each column has only a few cases, and two bit operations cover them:
Time O(1)Space O(1)
The full walkthrough and code are part of Premium
9
15