Skip to content

Instantly share code, notes, and snippets.

@jackmott jackmott/add.c
Last active Nov 30, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.