Think in whole bits:
public static int getSum(int p, int q)
{
int result = p ^ q;
int carry = (p & q) << 1;
if (carry != 0) {
return getSum(result, carry);
}
return result;
}
This recursion ends because the transfer has successively more bits 0 on the right (maximum 32 iterations).
You can easily write this as a loop with p = result; q = carry; p = result; q = carry;,
Another feature of algorithmic research does not go too far in differentiating cases. Above, you can also take the condition if ((result & carry) != 0).
source
share