Saturday, December 5, 2009

How to add two numbers without using the plus operator?

Actually,
SUM   = A XOR B
CARRY = A AND B
Recursive:
int add(int a, int b){
            if (!a) return b;
            else
                 return add((a & b) << 1, a ^ b);
      }

Iterative

unsigned long add(unsigned long integer1, unsigned long integer2)
{
    unsigned long xor, and, temp;

    and = integer1 & integer2; /* Obtain the carry bits */
    xor = integer1 ^ integer2; /* resulting bits */

    while(and != 0 ) /* stop when carry bits are gone */
    {
        and <<= 1; /* shifting the carry bits one space */
        temp = xor ^ and; /* hold the new xor result bits*/
        and &= xor; /* clear the previous carry bits and assign the new
carry bits */
        xor = temp; /* resulting bits */
    }
    return xor; /* final result */







On a wicked note, you can add two numbers wihtout using the + operator as follows
a - (- b)

Other way is to use ++ operator:
           int a=10,b=20;
          while(b--) a++;
           printf("Sum is :%d",a);  

No comments:

Post a Comment