HDU1002--A + B Problem II

来源:互联网 发布:中关村数据恢复价格 编辑:程序博客网 时间:2024/04/28 05:40

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 203220    Accepted Submission(s): 39047


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
21 2112233445566778899 998877665544332211
 

Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110
 

Author
Ignatius.L
 
解析:其实就是实现加法运算,数组模拟大数加法,输入的时候采用字符串输入,一定要考虑到如果两数的长度不同的情况,还有加法进位的处理,最后还有输出的+=左右都有空格,最后那组数据不再输出空行,需要考虑的情况还真多,wa了几次哈!
贴一下自己的代码
#include<iostream>#include <string>#include<algorithm>using std::endl;using std::cin;using std::cout;using std::string;int main(){#ifdef LOCALfreopen("input.txt" , "r" , stdin);freopen("output.txt" , "w" , stdout);#endifint T;cin >> T;string a , b , sum;for(int cases = 1; cases<=T; ++cases){sum.clear();cin >> a >> b;cout << "Case " << cases << ":" << endl;cout << a <<" + "<<b << " = ";int c = 0 ;reverse(a.begin() , a.end());reverse(b.begin() , b.end());int alength = a.length();int blength = b.length();int length = alength;//使两个字符串的长度相等,补齐零if(alength < blength){for(int i=alength; i<blength; ++i){a += '0';}length = blength;}if(blength < alength){for(int i=blength; i<alength; ++i){b +='0';}length = alength;}//进行加法计算,c为进位for(int i=0; i<length; ++i){int temp = (a[i] - '0') + (b[i] - '0') +c;c = temp/10;sum += (temp%10 + '0');}//最高位的进位如果不为0的话则进位if(c!=0){sum += (c +'0');}//结果转置reverse(sum.begin() , sum.end());cout << sum << endl;//控制最后的那组数据不再输出空行if(cases != T){cout << endl;}}}


0 0