Created
June 27, 2011 21:27
-
-
Save OrangeTide/1049882 to your computer and use it in GitHub Desktop.
add without using +,++ or -,--
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* otadd0.c : add without using +,++ or -,-- */ | |
/* clean: | |
int add(int a, int b) | |
{ | |
int r,n,c; | |
for(r=c=0,n=1;n;n<<=1) { | |
c = (a & b) ^ (c & (a ^ b)); | |
c <<= 1; | |
r |= (a ^ b ^ c) & n; | |
} | |
return r; | |
} | |
*/ | |
/* compressed */ | |
int add(int a,int b){ | |
int r,n,c;for(r=c=0,n=1;n;n<<=1){c=(a&b)^(c&(a^b));c<<=1;r|=(a^b^c)&n;}return r; | |
} | |
/** test code **/ | |
/* to use: | |
* ./otadd0 33 66 | |
* ./otadd0 -5 -3 | |
* ... | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
int main(int argc, char **argv) | |
{ | |
printf("%d\n",add(strtol(argv[1],0,0),strtol(argv[2],0,0))); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment