C - A + B Problem II
依旧是加法的计算!
题干:
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
主要思路就是小学的计算方法,从个位开始对齐相加,若超过10,则个位数相加以后对10取余,然后个位数相加以后除10再加到十位上,以此类推。但是还要注意两个数字的位数不同的情况。
在C语言中,头文件为(#include<string.h>)中的strlen函数,在使用时需将调用函数strlen的结果赋值给一个int型的变量,形如:int a;a=strlen(b);意思是计算出字符串b的长度并将其值赋值给a,需要强调的是在计算字符串的长度时,是不包括’\0’的!!!!!!
所以在C++中也是一样的,只不过在调用函数时写法发生了改变。形如:int a;a=b.lenth;
根据题目要求,输入的数组大小已经超出了我们正常使用的数据类型,故可以使用字符串存放数字,然后进行计算。
代码如下:
#include<iostream>
#define _ ios_base::sync_with_stdio(0),cin.tie(0);//加快cin的速度
using namespace std;
string add(string a,string b)
{
string temp1,temp2;
//将大的数给字符串temp2,小的数给字符串temp1
temp1=(a.length()<=b.length())?a:b;//若a的比b的小,则temp1就被a赋值,否则也计算当a的比b的大时,则temp1就被b赋值
temp2=(a.length()>b.length())?a:b;//与上同理
//将小数加到大数上(从个位开始)
int c=0;//进位
int i,ben=0;//本位
int len=temp1.length();
int j=temp2.length()-1;//从个位数开始,由于数组的下标从0开始,故个位数应该为字符串的长度减1
for(i=len-1;i>=0;i--,j--)
{
int tt=(temp1[i]-'0'+temp2[j]-'0'+c);//将字符转化为整型计算
ben=tt%10;//无论两个数加起来超没超过10,直接对10取余,少了一步判断
temp2[j]=ben+'0';//将数字转化成字符
c=tt/10;//两个数加起来除10,为进位做准备
}
while(j>=0)//表示小的那个数已经与大的数的相应位数已相加,大的数还有剩余位数,并且经过上一步计算进位的数字仍被保留 ;或者是两个位数相同,但是最后可能会有进位,还有进一步计算
{
int tt=(temp2[j]-'0'+c);
ben=tt%10;
temp2[j]=ben+'0';
c=tt/10;
j--;
}
if(c!=0)
{
temp2=char(c+'0')+temp2;//temp2表示的就是temp2[0]
}
return temp2;
}
int main()
{
int t;
cin>>t;
for(int i=0;i<t;i++)
{
string a,b;
cin>>a>>b;
cout<<"Case "<<i+1<<":"<<endl<<a<<" + "<<b<<" = "<<add(a,b)<<endl;
if(i!=t-1)
{
cout<<endl;
}
}
return 0;
}