Skip to content
BytePatterns

Add Two Numbers Without Plus

MediumBit Manipulation#bitwise-add#carry-propagation#twos-complement~25m

Problem

A tiny chip exposes only bitwise instructions: AND, OR, XOR and shifts. Write the addition routine it needs: given two 32-bit signed integers a and b, return a + b without using + or - on them. Both inputs and the sum lie between -1,000 and 1,000, and the result must match ordinary 32-bit two's complement addition, including for negative numbers.

Examples

Input:  a = 1, b = 2
Output: 3
Input:  a = -5, b = 3
Output: -2
Input:  a = -7, b = -8
Output: -15
Why:    edge case, both inputs are negative

Hints

0 / 3

Stuck on the idea rather than the code? Binary and Bitwise Ops covers it.