首页 > 代码库 > HDU1002--A + B Problem II
HDU1002--A + B Problem II
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
2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3 Case 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 LOCAL freopen("input.txt" , "r" , stdin); freopen("output.txt" , "w" , stdout); #endif int 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; } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。