A + B Problem II (大数加法)

来源:互联网 发布:淘宝童装店简介 编辑:程序博客网 时间:2024/05/21 16:23

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 366434    Accepted Submission(s): 71355
Problem Description
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


此题即为大数的加法问题;

大整数加法的模拟,这里模拟小学生加法运算,用字符串储存大整数的数值。

首先看一下小学生的加法:987 + 345 = 1332

从个位开始模拟, 5 + 7 = 12 个位取2,后一位进1,(若没有进位则进位为0)

十位:4 + 8 = 12 + 1(次低位的进位=1) = 13 十位取值为3,后一位进1 (若没有进位则进位为0)

百位:3 + 9 = 12 + 1(次低位的进为=1) = 13十位取值为3,后一位进1 (若没有进位则进位为0)

千位:(次低位的进位=1) 则为 1                       

下面就是大整数加法代码:字符串进行存储数据,例:123 + 234  

首先介绍一下字符转化为整数 ’2‘ - ’0‘ = 2,即为'b' - '0' = b (b为数字字符)



复制代码
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
#define M 1000
using namespace std;
char n1[M],n2[M],sum[M];//n1,n2为加数的字符串,sum为和的字符串 
int m1[M],m2[M];//m1,m2分别为n1,n2字符串的数字的倒序 
int t;
int main()
{
cin>>t;
int k=1;
while(t--)
{
int i,j; 
memset(sum,0,M*sizeof(char));//将sum字符串清零 
cin>>n1>>n2;
memset(m1,0,sizeof(m1));//将m1,m2数字清零 
memset(m2,0,sizeof(m2));
int l1=strlen(n1);
int l2=strlen(n2);
//将n1,n2翻转变成数字存入m1,m2 
for(i=0;i<l1;i++)
m1[i]=n1[l1-i-1]-'0';
for(i=0;i<l2;i++)
m2[i]=n2[l2-i-1]-'0';
int c=0;//c为进位数 ,初始为0 
//进行加法运算 
for(i=0;i<l1||i<l2;i++)
{
//sum【i】存储当前的计算结果的个位 
sum[i]=(m1[i]+m2[i]+c)%10+'0';
//c储存的是当前计算的进位 
c=(m1[i]+m2[i]+c)/10;
}
//加上最后一个进位 
sum[i]=c+'0';
sum[i+1]='\0';
int l=strlen(sum);
cout<<"Case "<<k++<<":"<<endl;
cout<<n1<<" + "<<n2<<" = ";
//如果相加为0 
if(l==2&&sum[0]=='0'&&sum[1]=='0')
{
cout<<"0"<<endl;
continue;
}
//倒序输出sum 
for(i=l-1;sum[i]=='0';i--);//倒着查找第一个不为0的数之后开始输出 
for(int j=i;j>=0;j--)
cout<<sum[j];
cout<<endl;
if(t)
cout<<endl;
}
return 0;

复制代码

人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想