C - Adding the numbers in 2 strings together if a different length -
if had 2 strings:
a = "1234" b = "4321"
i add 2 numbers this:
for(i=0; i<width-1; i++){ sum = (a[width-2-i]-48) + (b[width-2-i]-48) + carry; carry = 0; if(sum > 9){ carry = 1; sum-=10; } answer[i] = sum+48; } if(carry) answer[i++] = carry+48; answer[i]= 0;
and reverse (width equal strlen(a)).
how same thing if following?
a = "12345" b = "4321"
would need reallocate memory? or what?
(btw - the problem i'm trying solve using many numbers 50 digits, strtoul or strtoull out of question understand. here's code far.)
int getcharval(const char *s, int idx) { if (idx < strlen(s)) return s[strlen(s) - idx - 1] - 48; return 0; } void add() { const char *a = "1234"; const char *b = "13210"; char answer[256]; int i, wa=strlen(a), wb=strlen(b), width, sum, carry; width = wa > wb ? wa : wb; for(i=0; i<width; i++){ char ca = getcharval(a, i); char cb = getcharval(b, i); printf("%d %d\n", ca, cb); sum = ca + cb + carry; carry = 0; if(sum > 9){ carry = 1; sum-=10; } answer[i] = sum+48; } if(carry) answer[i++] = carry+48; answer[i]= 0; (i = 0; < strlen(answer) / 2; i++) { char t = answer[i]; answer[i] = answer[strlen(answer) - - 1]; answer[strlen(answer) - - 1] = t; } printf("%s\n", answer); }
Comments
Post a Comment