public int add(int a, int b){
while (b != 0){
int carry = (a & b) ;
a = a ^ b;
b = carry << 1;
}
Yes, like many answers here, it works like rudimentary school math for adding two numbers. But in Binary way.
What does a&b give us? It gives ones at all places which will trigger a carry forward. For examples, adding 1101 and 0101, only the 0th and 2nd position from right triggers carry forward. So only that will be 0101 which is obtained by a&b. But when doing carry in normal addition, we move one position left. That is why in 3rd statement of code, the carry is moved one position left. So carry becomes 01010.
What does a^b give us? Any bit that is not counted above is included. In the above step, we included impact of 0th and 2nd bit. Now we need to include other bits which have 1. That will be 3rd from right giving is 1000. The value assigned to a becomes 1000.
Now all we have to do is add these again, using the same steps above.
Adding 01010 and 01000. Only common one is 3rd position, so a&b gives 01000 and carry eventually becomes 10000 after the shift.
To count the remaining bits, a^b becomes 00010 and gets assigned to a.
Loop continues. As carry above is not zero yet.
Adding 10000 and 00010. No common 1's bit. So carry becomes 0.
a^b becomes 10010 and gets assigned to a.
As carry is zero, whatever in a, which is 10010 becomes the answer!
Much better to understand with examples, smaller examples.