DSA problem
Sum of Two Integers
Given two integers a and b, return the sum of the two integers without using the operators + and -.
The trick is to reproduce binary addition using only bitwise operations. For any two bits, their XOR a ^ b gives the sum without carry, and their AND a & b gives the positions that generate a carry. Shifting that carry left by one, (a & b) << 1, moves it to the next higher position where it must still be added in.
Repeat the process: set a to the partial sum and b to the shifted carry, looping until the carry becomes 0. At that point a holds the final sum. This mirrors how a ripple-carry adder works in hardware and naturally handles negative numbers via two's complement.
Examples
a = 1, b = 23a = 2, b = 35a = -2, b = 31Constraints
- -1000 <= a, b <= 1000
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.