Add without using any arithmetic operators

From Embedded Systems Learning Academy
Jump to: navigation, search

Interview Question : Add without using any arithmetic operators

Approach: What choice do we have if not to use any operators for addition? Bits!!
1) XOR the two numbers to perform addition without any carry.
2) AND them and left shift to perform 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
}