Sum of Two Integers

MediumBit manipulation

Given two integers a and b, return their sum.

The challenge is to do it without the + and - operators, using bitwise operators instead. The tests can only check the answers, so holding to that is up to you.

Examples

Example 1
Input:  a = 7, b = 5
Output: 12

0111 and 0101 share bits 0 and 2, so those carry, and the sum is 1100, which is 12.

Example 2
Input:  a = -4, b = 10
Output: 6

Negative numbers work too: -4 plus 10 is 6.

Constraints

  • -1000 ≤ a, b ≤ 1000

Stuck?

Hint 1

a ^ b adds the bits without carrying, and (a & b) << 1 is exactly the carry.

Hint 2

Adding the carry can make a new carry, so repeat: set a to the sum without carry and b to the carry until b is 0. Negative numbers work too, since the operators use 32-bit two’s complement.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur