I just wanted to add strings in any base form (example 1101+100 = 10001 in base-2 but it could be added using any base-form like in base-3 to base-36) and I'm having a big trouble with my code because it gave me incorrect results.
addition(char st[], char st2[], int base){
int i, j, carry = 0, ans, len, o=0, z=1, l=0;
char final[50];
if(strlen(st)>=strlen(st2))
len = strlen(st);
else
len = strlen(st2);
for(i=len; i>=0; i--){
if(isdigit(st[i])&&isdigit(st2[j])){ //if both addends are digits
ans = (st[i] - '0') + (st2[i] - '0') + carry;
}
else if(isdigit(st[i])&&isalpha(st2[j])){ //if first addend is a digit and second addend is an alphabet
ans = (st[i] - '0') + (st2[j] - 'A'+10) + carry;
}
else if(isalpha(st[i])&&isdigit(st2[j])){ //if first addend is an alphabet and second addend is a digit
ans = (st[i] - 'A'+10) + (st2[j] - '0') + carry;
}
else if(isalpha(st[i])&&isalpha(st2[j])){ //if both addends are alphabet
ans = (st[i] - 'A'+10) + (st2[j] - 'A'+10) + carry;
}
if(ans > base){
ans = ans - base;
carry = ans - base;
}
else if(ans == base){
ans = ans - base;
carry = 1;
}
if(ans >= 0 && ans <= 9)
final[i] = ans + 49;
else if(ans >= 65 && ans <= 90)
final[i] = ans + 65;
printf("%c", final[i]);
}
}
I really need help about this code. Thanks :-)