题解 | #Integer Inquiry#
Integer Inquiry
https://www.nowcoder.com/practice/df03906024d742cc919a64c22983f5e1
#include <string.h> #include <algorithm> #include <iostream> #define MAX_DIGITS 1000 using namespace std; void add(char a[], char b[], char c[]) { int alen = strlen(a), blen = strlen(b); c[max(alen, blen)] = '\0'; int carry = 0, sum = 0; int i, j; for (i=alen-1, j=blen-1; i>= 0 || j>=0; i--, j--) { int adigit = (i >= 0 ? a[i] - '0' : 0); //converting char 'i' to int i int bdigit = (j >= 0 ? b[j] - '0' : 0); sum = adigit + bdigit + carry; carry = sum / 10; c[max(i, j)] = sum % 10 + '0'; } if(carry == 1){ //最高位进位 for(int k=strlen(c)+1;k>=1;k--) c[k]=c[k-1]; c[0]='1'; } } int main(void) { char a[MAX_DIGITS], b[MAX_DIGITS], c[MAX_DIGITS]; scanf("%s", a); scanf("%s", b); add(a, b, c); while(scanf("%s", a)!=EOF){ memcpy(b,c,sizeof(c)); add(a, b, c); } printf("%s", c); return 0; }