AAlgoLoopSpaced repetition for LeetCode
MEDIUMBit ManipulationLeetCode ↗

Sum of Two Integers

The key idea

Binary addition splits into two independent pieces: a XOR b is the sum without carry, and (a AND b) << 1 is the carry. Feed the carry back in and repeat until it is 0 — that loop reproduces + using only bitwise ops.

Problem

Given two integers a and b, return the sum of the two integers without using the operators + and -.

You may use any other operator, including the bitwise operators (AND, OR, XOR, shifts). The idea is to rebuild addition from its two parts: the column-by-column sum and the carry.

Constraints

Examples

Input: a = 1, b = 2 Output: 3
Input: a = -2, b = 3 Output: 1
Input: a = 5, b = 7 Output: 12

Complexity

Time: O(1) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Bit Manipulation problems