#include <stdio.h> #include <string.h> #define MAX(a,b) (a > b ? a : b) char * reverse(char *s) { int len = strlen(s); char tmp = 0; int i; for (i = 0; i < len / 2; i++) { //printf("%d %c\n", len - i - 1, s[len - i - 1]); tmp = s[len - i - 1]; s[len - i - 1] = s[i]; s[i] = tmp; } return s; } int main(void) { // for (int i = 0; i < 5000; i++) { // printf("9"); // } //printf("\n"); char a[5001] = {'\0' }, b[5001] = { '\0' }; char out[6000] = { 0 }; scanf("%s", &a[0]); scanf("%s", &b[0]); int lena = strlen(a); int lenb = strlen(b); int carry = 0; int i; reverse(a); reverse(b); for (i = 0; i < MAX(lena, lenb); i++) { int ai = a[i] ? a[i] - '0' : 0; int bi = b[i] ? b[i] - '0' : 0; int sum = ai + bi + carry; if (sum > 9) { out[i] = sum - 10 + '0'; carry = 1; } else { out[i] = sum + '0'; carry = 0; } } if (carry) out[i] = carry + '0'; reverse(out); printf("%s\n", out); return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | #include <stdio.h> #include <string.h> #define MAX(a,b) (a > b ? a : b) char * reverse(char *s) { int len = strlen(s); char tmp = 0; int i; for (i = 0; i < len / 2; i++) { //printf("%d %c\n", len - i - 1, s[len - i - 1]); tmp = s[len - i - 1]; s[len - i - 1] = s[i]; s[i] = tmp; } return s; } int main(void) { // for (int i = 0; i < 5000; i++) { // printf("9"); // } //printf("\n"); char a[5001] = {'\0' }, b[5001] = { '\0' }; char out[6000] = { 0 }; scanf("%s", &a[0]); scanf("%s", &b[0]); int lena = strlen(a); int lenb = strlen(b); int carry = 0; int i; reverse(a); reverse(b); for (i = 0; i < MAX(lena, lenb); i++) { int ai = a[i] ? a[i] - '0' : 0; int bi = b[i] ? b[i] - '0' : 0; int sum = ai + bi + carry; if (sum > 9) { out[i] = sum - 10 + '0'; carry = 1; } else { out[i] = sum + '0'; carry = 0; } } if (carry) out[i] = carry + '0'; reverse(out); printf("%s\n", out); return 0; } |