Add without using any arithmetic operators
From Embedded Systems Learning Academy
Revision as of 04:25, 13 December 2016 by Proj user16 (talk | contribs) (Created page with "== Interview Question : Add without using any arithmetic operators == '''''Approach:''''' What choice do we have if not to use any operators for addition? '''''Bits!!''''' <br...")
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
}