Given two integers a and b, return the sum of the two integers without using the operators + and -.
a = 1, b = 12a = 2, b = 35Binary addition works column by column. XOR at each bit gives the sum-without-carry. AND at each bit gives where two 1s overlap — that's the carry. Shifting the carry left by 1 places it in the correct next column. We repeat until there is no more carry (b becomes 0). This exactly mimics how hardware adders work.
Adding one at a time with increments is not allowed either, and it would be slow. We can rebuild addition from bit operations, just like a circuit does.
XOR adds two bits without the carry: 1 plus 1 gives 0. AND finds where both bits are 1, which is where a carry is produced. Shift those carries left by one, because a carry moves into the next column. Repeat with the partial sum and the carries, until no carry is left.
XOR is sum without carry, AND shifted is the carry. Repeat until the carry is zero.
Run the animation above on your own input, or watch the 1:31 video explanation of Sum of Two Integers with a dry run and Java code.