大数加法——HOJ1002

HOJ1002


/*

算法原理:
***********************************************************

①用数组存储数字(输入的顺序与大数的个十百千万位刚好相反)
②在加的过程中转换成数字(-‘0’)
/ 运算得到进位的大小(数字表示)
% 运算得到此位的数字,转换为字符存储到temp(+‘0’)
③注意最后的进位,相加最多进一位,因为temp是逆序,
直接在后一位赋进位的值即可
④反转数组得到结果

***********************************************************

*/
#include<iostream>
#include<stdio.h>
#include<math.h>

using namespace std;

const int Length = 1000;

int carry(int n)					//计算进位
{
	return n*n >= 10 ? n / 10 : 0;
}	

void stringAdd(char* lhs, char *rhs, char* result)	//得到的结果是正序
{
	int i = strlen(lhs) , j = strlen(rhs);			
	int curAns = 0, ncarry = 0, k = 0;		//curAns 表示lhs和rhs相同位相加的digital结果
							//ncarry 表示向高一位的进位
	char temp[Length] = { 0 };
	while (i&&j)
	{
		curAns = (lhs[--i] + rhs[--j] - 96) + ncarry;//先减去1,因为数组被初始化为0
		ncarry = carry(curAns);
		temp[k++] = curAns % 10 + 48;
	}
	while (i)
	{
		curAns = (lhs[--i] - 48)  + ncarry;
		ncarry = carry(curAns);
		temp[k++] = curAns % 10 + 48;
	}
	while (j)
	{
		curAns = (rhs[--j] - 48)  + ncarry;
		ncarry = carry(curAns);
		temp[k++] = curAns % 10 + 48;
	}
	if (curAns >= 10)						//处理进位的情况
	{
		temp[k++] = carry(curAns) + 48;
	}

	i = 0;
	while(k)							//反转顺序
		result[i++] = temp[--k];
	
}


int main()
{

	int n, i = 0;
	cin >> n;
	char result[Length + 1] = { 0 }, a[Length] = { 0 }, b[Length] = { 0 };
	while(n)<span style="white-space:pre">							</span><span style="font-family: Arial, Helvetica, sans-serif;">//注意初始化</span>

	{ 
		n--, i++;
		cin >> a >> b;
		stringAdd(a, b, result);
		printf("Case %d:\n%s + %s = %s\n", i, a, b, result);
	}
	
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值