Sum of Two Integers

Return the sum of two integers a and b without using the + or − operators.

A way to picture it

Remember column addition from school? XOR is you writing down each column's digit while ignoring carries. AND is you noticing where two 1s meet and a carry is born. Shift the carries left and add again, until nothing is left to carry.

How to approach it

a ^ b is the sum without carries; (a & b) << 1 is the carries. Repeat with those two until the carry is 0.

Example

Input: {"a":1,"b":2}. Output: 3.

Complexity: O(1) time and O(1) space. At most 32 rounds for 32-bit integers.

This page includes an animated walkthrough, Java and Python solutions, and a question to check your understanding.