Add without plus

From Embedded Systems Learning Academy
Jump to: navigation, search

Interview Question : Add without using operator +

The task here is to write a function that adds two numbers without using the operator + or any other arithmetic operator.
Approach: What choice do we have if we cant use operators? Bits!!
1) XOR the two numbers - This gives their sum without any carry.
2) AND the numbers and left shift to do a carry without any further addition.
3) Recurse until there is nothing left to carry.

int addNoOperator (int x, int y)
{
	if (y==0) return x;  // Base case
	int add = x ^ y; // add without any carry
	int carry = (x & y) << 1; // carry, but no addition
	return addNoOperator (add, carry); // recurse with add + carry
}