题解 | #高精度整数加法#
高精度整数加法
http://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
#include<stdio.h> #include<string.h> int add(int a,int b,int*carry_in){ int sum = a+b+*carry_in; if(sum>9){ *carry_in = 1; return sum-10; } else{ *carry_in = 0; return sum; } } int main(){ char s1[10000] = {0}; char s2[10000] = {0}; scanf("%s",s1); scanf("%s",s2); int len1 = strlen(s1); int len2 = strlen(s2); int len_max = len1>len2?len1:len2; if(len1>len2){ int d = len1-len2; for(int i=len2-1;i>=0;i--){ s2[i+d] = s2[i]; } for(int i=0;i<d;i++){ s2[i] = '0'; } } else if(len1<len2){ int d = len2-len1; for(int i=len1-1;i>=0;i--){ s1[i+d] = s1[i]; } for(int i=0;i<d;i++){ s1[i] = '0'; } } int carry_in = 0; int r; int k=0; char res[10001] = {0}; for(int i=len_max-1;i>=0;i--){ int a = s1[i]-48; int b = s2[i]-48; r = add(a,b,&carry_in); res[k++] = r+48; } if(carry_in==1) res[k++] = 49; for(int i=k-1;i>=0;i--) printf("%c",res[i]); }