The approach is to add two numbers using bitwise operations. Let's first go through some observations:
a & b will have only those bits set which are set in both a and b.
a ^ b will have only those bits set which are set in either a or b but not in both.
If we want to calculate the sum of a and b such that a and b has no common set bit, then a ^ b is same as a + b. So, we can say that a + b without carry = a ^ b.
How to handle the case when we have carry, that is a and b has common set bits?
To calculate the carry, we know that carry will only have the common set bits of a and b, shifted 1 place to the left. So, we can say that carry = (a & b) << 1.
Now, the problem is reduced to calculating the sum of (a + b without carry) and carry. This is again the same problem: sum of two numbers where the firstnumber = (a + b without carry) and second number = carry. So, we can repeatedly calculate carry and sum without carry, till carry is not reduced to 0.
Working:
Note: The above approach will work perfectly for languages like C++, Java, C# and JavaScript in which an integer has a size of 32 bits but in Python, we need to handle the overflow separately by creating a 32-bit mask of 1's.
Below is the implementation of the above algorithm:
Output
1
Time Complexity: O(max(number of bits in a, number of bits in b)) Auxiliary Space: O(1)