Bit Manipulation · Easy

Add Two Integers Without Using + or -

Solve it on DeVert Campus - free code runner

Problem

Given two integers A and B, compute their sum without using the +, -, *, or / operators; you may use bitwise operations, loops, and comparisons. Print the resulting sum. A and B may be negative.

Input and output

Input: A single line containing two space-separated integers, A and B. Output: A single line containing the sum of A and B.

Example

Input:
3 5
Output:
8

Constraints

-10^9 <= A, B <= 10^9 (the true sum fits within a 32-bit signed integer)

Key observation

This technique correctly handles NEGATIVE operands too, since fixed-width two's complement representation makes bitwise operations behave consistently regardless of sign - no special-casing needed for negative inputs.

Intuition

Compute the sum of two integers using only bitwise operations, without the + or - operators. Brute force: There's no meaningfully 'slower but simpler' alternative here since + is explicitly disallowed - the bit-by-bit carry propagation IS the direct simulation of how binary addition actually works at the hardware level. Optimised: XOR naturally computes 'sum ignoring carries' (since it flips a bit exactly when the two inputs disagree, matching what addition-without-carry would produce), while AND-then-shift-left directly computes exactly which positions generate a carry into the NEXT bit - repeating this until the carry vanishes exactly mimics how a hardware adder circuit works internally.

Step by step

1. Compute A XOR B - this gives the sum of A and B IGNORING any carries. 2. Compute (A AND B) shifted left by one - this gives exactly the CARRIES that still need to be added in. 3. Repeat this XOR/carry step, feeding the new carry back in as one of the operands each time, until there's no carry left (it becomes 0).

Complexity

Time: O(log(max value)) in the worst case - the number of iterations is bounded by the number of bits, since each iteration shifts the carry further left. Space: O(1) - just a few integer variables.

Edge cases

Either or both operands can be 0 or negative; the result can also be negative.

Interview tip

Be ready to mention that this exact bit-by-bit carry-propagation logic mirrors how actual CPU hardware adders work - a great talking point connecting this puzzle to real computer architecture.

All DSA problems