Without previous knowledge of the equation, a+b = a^b + (a&b)*2
, we can think of another solution. This solution is O(logK)
where K is the maximum possible value of S and X. That is, if S and X are unsigned int
then K is 2^32 - 1
.
Start from the MSB of S and X. With the information that whether summing this bit must provide carry or not, we can check for this bit with condition that whether summing the bits to the right should provide carry or not.
Case1 ) summing must not provide carry
S X | need carry from right
------------------------------
0 0 | no (a = 0, b = 0)
0 1 | impossible
1 0 | yes (a = 0, b = 0)
1 1 | no (a = 1, b = 0 or 0,1)
Case2 ) summing must provide carry
S X | need carry from right
------------------------------
0 0 | no (a = 1, b = 1)
0 1 | yes (a = 1, b = 0 or 0,1)
1 0 | yes (a = 1, b = 1)
1 1 | impossible
There is a special case for the MSB where the carry doesn't matter.
Case3 ) don't care
S X | need carry from right
------------------------------
0 0 | no (a = 0, b = 0 or 1,1)
0 1 | yes (a = 1, b = 0 or 0,1)
1 0 | yes (a = 0, b = 0 or 1,1)
1 1 | no (a = 1, b = 0 or 0,1)
Lastly, the LSB must end with 'no need carry from right'.
The implementation and test code is here. It compares the output of the accepted solution and this solution.