首页 > 代码库 > 7月17日

7月17日

一:

大整数相加问题

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. 

InputThe 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. 
OutputFor 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

分析:对于此题做法有两种:其一,使2字符串的中的字符数字减去‘0‘,逐个相加大于等于10的可以使本位减10,下一位自增1,后面的处理就非常简单了;其二,便是读入字符串后先让各个字符减‘0‘,一一对应存入整形数组中;之后再相加。对于2种方法大致是相同的,都要从后面向前加,逢十进位,以及数组初始化均要初始为0,一边方便运算。

参考网址 http://blog.csdn.net/oosuifengoo/article/details/7089144


源代码:

#include <iostream>
using namespace std;
#include<stdio.h>
#include<string.h>
int main()
{
int n,m;
scanf("%d",&n);
m=1;
while(m<=n)
{
char a[1000],b[1000];
int i,c[1000]={0},la,lb,q;
scanf("%s %s",a,b);
la=strlen(a)-1;//计算给定字符串的(unsigned int型)长度,不包括‘\0‘在内,返回s的长度,不包括结束符NULL。
lb=strlen(b)-1;//ala,lb代表数组的长度
q=la>lb?la:lb;//把字符长度长的赋给q
for(i=0;la>=0;i++,la--)
c[i]=a[la]-‘0‘;
for(i=0;lb>=0;lb--,i++)
{
c[i]+=b[lb]-‘0‘;
if(c[i]>=10)
{
c[i+1]++;
c[i]-=10;
}
}
printf("Case %d:\n",m);
printf("%s + %s = ",a,b);
if(c[q+1]!=0)
printf("%d",c[q+1]);//用于多出一位的情况如1+99
for(q;q>=0;q--)
printf("%d",c[q]);//从大位输到小位
printf("\n");//格式
if(m!=n)
printf("\n");//格式
m++;
}
return 0;
}

7月17日