Bitwise recursive addition of two integers
When adding two binary numbers by hand we keep the carry bits in mind and add it at the same time. But to do same thing in program we need a lot of checks. Recursive solution can be imagined as addition of carry and a^b (two inputs) until carry becomes 0.
Input : int x = 45, y = 45 Output : 90 Input : int x = 4, y = 78 Output : 82
Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits.
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.
One important observation is, if (x & y) becomes 0, then result is x ^ y.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.