A + B Problem II

之前总是在查阅别人的文档,看着其他人的博客,自己心里总有一份冲动,想记录一下自己学习的经历。学习算法有一段时间了,于是想从算法开始自己的博客生涯O(∩_∩)O~~

今天在网上看了一道大数相加(高精度)的题目,题目很简单,但是体现了算法编程的细心之处。

题目:A + B Problem II

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

/*注意哦这里是两个test之间会有一个空行*/

Case 2:

112233445566778899 + 998877665544332211 = 1111111111111111110

/*在最后一个test输出之后是不需要空行的*/

 #include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std; int main()
{
int n;
cin>>n;
int t = ;
while(n--)
{
t++;
char a[];
char b[];
char c[] = {''}; //c数组用来存放两数相加之和,需要初始化一下
cin>>a; //cin会忽略回车、空格、tab键
cin>>b;
int k,sum;
k = strlen(a)>strlen(b)?strlen(a):strlen(b); //k 取两个长整数中较长的一个
a[k+]='\0'; // 对长整数之后的一位赋值'\0' 结束标志
sum = ; //累加器
for(int i = strlen(a)-,j=strlen(b)-;j>=||i>=;i--,j--,k--)
{
if(i>=) sum+=a[i]-'';
if(j>=) sum+=b[j]-'';
c[k] = sum% + '';
sum /= ;
}
if(sum!=)
c[] = sum + '';
else
strcpy(c,&c[]);
printf("Case %d:\n",t);
printf("%s + %s = %s\n",a,b,c);
if(n!=) //最后一个test 不需要输出空行
printf("\n");
}
return ;
}
上一篇:Oracle客户端工具安装


下一篇:Oracle客户端的安装