参考代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> struct lennum{ int num; struct lennum *next; struct lennum *back; }; int main() { char strnum1[300],strnum2[300]; scanf("%s",strnum1); getchar(); scanf("%s",strnum2); // 记录非负整数 从个位数开始存储 struct lennum *head1=NULL,*head2=NULL,*p=NULL,*q=NULL,*temphead=NULL; // 非负整数1 for(int i=strlen(strnum1)-1;i>=0;i--) if(i==strlen(strnum1)-1) { q = (struct lennum *)malloc(sizeof(struct lennum)); q->num = strnum1[i]-'0'; q->back=NULL; q->next=NULL; head1=p=q; } else { q = (struct lennum *)malloc(sizeof(struct lennum)); q->num = strnum1[i]-'0'; q->back=NULL; q->next=NULL; p->next=q; q->back=p; p=q; } // 非负整数2 for(int i=strlen(strnum2)-1;i>=0;i--) if(i==strlen(strnum2)-1) { q = (struct lennum *)malloc(sizeof(struct lennum)); q->num = strnum2[i]-'0'; q->back=NULL; q->next=NULL; head2=p=q; } else { q = (struct lennum *)malloc(sizeof(struct lennum)); q->num = strnum2[i]-'0'; q->back=NULL; q->next=NULL; p->next=q; q->back=p; p=q; } // 短的整数加到长的整数上去 q指向短的 p指向长的 if(strlen(strnum1)>strlen(strnum2)) temphead=p=head1,q=head2; else temphead=p=head2,q=head1; while(q!=NULL) { p->num=p->num+q->num; p=p->next; q=q->next; } // 进位 p=temphead; while(p->next!=NULL) { p->next->num=p->next->num + p->num/10; p->num=p->num%10; p=p->next; } // 最高位进位 while(p->num>=10) { q = (struct lennum *)malloc(sizeof(struct lennum)); q->num = p->num/10; q->back=NULL; q->next=NULL; p->next=q; q->back=p; p->num=p->num%10; p=q; } // 输出 while(p!=NULL) { printf("%d",p->num); p=p->back; } }
0.0分
0 人评分