【杭电-oj】-1002-A + B Problem II(大数相加)
2016-07-18 15:49
525 查看
A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 314006 Accepted Submission(s): 60840
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
用字符串存比较大的数,然后把数倒着写,因为比较利于计算,此时应注意方法,再判断最高位有没有进位即可。
但是师傅建议我这么写,记下,下道题试试。
初始化:
输出:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int main() { int n,num=0; char a[1010],b[1010]; //把数当做字符串用a,b存 int l1,l2,l3; int numa[1010]={0},numb[1010]={0}; //分别存储a,b准换为数字后的值 scanf("%d",&n); while(n--) { memset (numa,0,sizeof (numa)); memset (numb,0,sizeof (numb)); scanf("%s %s",a,b); l1=strlen(a); l2=strlen(b); l3=max(l1,l2); for(int i=0;i<l1;i++) numa[l1-i-1]=a[i]-'0'; //为了方便计算,把数倒着存,注意此处的技巧,会常用 for(int i=0;i<l2;i++) numb[l2-i-1]=b[i]-'0'; numb[l3]=0; for(int i=0;i<l3;i++) { numb[i]=numa[i]+numb[i]; if(numb[i]>9) { numb[i]=numb[i]-10; numb[i+1]++; } } num++; printf("Case %d:\n",num); printf("%s + %s = ",a,b); if(numb[l3]==0) //判断l3(最后一位)是否为零 { for(int i=l3-1;i>=0;i--) //倒着相加,倒着输出 printf("%d",numb[i]); printf("\n"); } else { for(int i=l3;i>=0;i--) printf("%d",numb[i]); printf("\n"); } if(n!=0) printf("\n"); } return 0; }
相关文章推荐
- Ubuntu 12 安装 MySQL 5.6.26 及 问题汇总
- Failed to load the JNI library "E:\JDK6.0\bin\client\jvm.dll"
- 移动端1px解决方案
- liunx命令之:命令链接ftp服务器
- 挪威石油基金将起诉大众汽车
- 【杭电oj】1997 - 汉诺塔VII(递归,思维)
- CentOS 下PHP5.3升级到PHP5.4步骤
- Invert Binary Tree
- 带权并查集 poj 1182
- Ubuntu 12 修改当前用户密码:new password is too simple
- Ubuntu 12 编译安装 PHP 5.4 及 问题汇总
- 关于Spring中的<context:annotation-config/>配置(开启注解)
- 水过杭电OJ hdu1004
- O(n) 方法求数列极差
- 【Xml配置文件的数据读取】
- 二维码的生成 lizbqrencode遇到的问题
- 如何设置PL/SQL语句的快捷键
- 中国豪车热度不减
- SQL注入全过程深入分析
- Ubuntu nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)