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);
}
}