蓝桥杯基础练习 高精度加法

#include <cmath>
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;

//全局变量在没有赋值以前系统默认为0,而局部变量在没有赋值以前的值是不确定的,
//所以在声明局部变量的时候一定要初始化。
//用char 数组保存字符串时,结尾总是添加'\0'(ASCII为十进制0) 
char a[105],b[105];
int c[105];
void Swap(char *p,int n)	//交换如输入1234,变成4321,这样个位在a[0],十位在a[1] 
{
	int i=0;
	while(i<=(n-1)/2)
	{
		swap(p[i],p[n-1-i]);
		i++;
	}
}
int Cnt(char *p)	//计算字符串个数 
{
	int tmp=0,i=0;
	while(p[i++])
		tmp++;
	return tmp;
}
int main()
{
	scanf("%s",a);
	scanf("%s",b);
	int c1=Cnt(a);
	int c2=Cnt(b);
	Swap(a,c1);
	Swap(b,c2);
	
	if(c1>c2)		//如1234\0 
	{				//  2300\0 (4321+32)
		while(c2<=c1)
		{
			if(c2==c1)
			{
				b[c2]='\0';
				c2++;	
			}
			else
			{
				b[c2]='0';
				c2++;
			}	
		}
	} 
	else if(c2>c1)	 //如 2300\0 
	{				//    1234\0  (32+4321) 
		while(c1<=c2)
		{
			if(c1==c2)
			{
				a[c1]='\0';
				c1++;
			}
			else
			{
				a[c1]='0';
				c1++;
			}
		}
	}
	int i=0;
	while(a[i]||b[i])
	{
		int tmp=c[i]+(a[i]-'0')+(b[i]-'0');
		c[i]=tmp%10;
		c[i+1]+=tmp/10;	
		i++;
	}
	if(c[i])	//最后的一位进位处理 
	{
		for(int k=i;k>=0;k--)
			cout<<c[k];
		cout<<endl;
	}
	else
	{
		for(int k=i-1;k>=0;k--)
			cout<<c[k];
		cout<<endl;
	}
	return 0;
} 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值