Thursday 2 August 2012

How to add two numbers without using the plus operator?


int main()
{
int a=10000,b=45,sum;
char *p;
p=(char *)a;
sum= (int)&p[b]; //adding a & b
printf("%d",sum);
return 0;
}


/*
the logic here is 
p[b]=*(p+b)
&p[b]=(p+b)

&(*(p+b)) will not result in
(*p)+b

actually p is not pointing to the value of a. instead the value of p(address) is changed to a.

*/


//one more solution is bit manipulation


int add(int x, int y) {
    int a, b;
    do {
        a = x & y;
        b = x ^ y;
        x = a << 1;
        y = b;
    } while (a);
    return b;
}


int main( void ){
    printf( "2 + 3 = %d", add(2,3));
    return 0;
}

No comments:

Post a Comment