原题链接:大整数加法
参考代码:
#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分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复