Skip to content

Instantly share code, notes, and snippets.

@jackmott
Last active November 30, 2018 15:26
Show Gist options
  • Save jackmott/e8453279aadd7d9cc59bd7bcd845cc5d to your computer and use it in GitHub Desktop.
Save jackmott/e8453279aadd7d9cc59bd7bcd845cc5d to your computer and use it in GitHub Desktop.
add
// Got a minute to revisit this question this morning and cleaned it up a lot
// - Jack
#define MAX(a,b) (((a)>(b))?(a):(b))
int ctoi(char c){
return (int)(c - '0');
}
char itoc(int i){
return (char)i+'0';
}
char* add(char * a,char*b){
int aLen = strlen(a);
int bLen = strlen(b);
//make room for null terminator and carry in result
int rLen = MAX(aLen,bLen)+1;
char* result = new char[rLen+1];
result[rLen] = 0;
int ai = aLen-1;
int bi = bLen-1;
int ri = rLen-1;
int carry = 0;
while(ri >= 0){
int aDigit = 0;
if(ai >= 0){
aDigit = ctoi(a[ai]);
}
int bDigit = 0;
if(bi >= 0){
bDigit = ctoi(b[bi]);
}
int sum = aDigit + bDigit + carry;
if(sum > 9){
sum -= 10;
carry = 1;
}
else{
carry = 0;
}
result[ri] = itoc(sum);
ri--;
bi--;
ai--;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment