大數相加-HDU 1002
超出long long長度的大數相加
存:字串 轉換數字:a[i] - ‘0’ 難點:進位的標記,定義整型變數temp標記進位值
HDU 1002
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
AC一例
#include <bits/stdc++.h> using namespace std; int main(){ string a,b; int t,c[1001],p=0; while(cin>>t){ for(int i=1;i<=t;i++){ cin>>a>>b; int alen,blen,clen=0,temp=0; alen = a.length()-1; blen = b.length()-1; while(alen>=0 && blen>=0){ c[clen++] = (temp + a[alen] - '0' + b[blen] - '0') % 10; temp = (temp + a[alen] - '0' + b[blen] - '0') / 10; alen--; blen--; } if(alen > blen) while(alen >= 0){ c[clen++] = (temp + a[alen] - '0') % 10; temp = (temp + a[alen] - '0') / 10; alen--; } else if(blen > alen) while(blen >= 0){ c[clen++] = (temp + b[blen] - '0') % 10; temp = (temp + b[blen] - '0') / 10; blen--; } c[clen] = temp; if(p) cout<<endl; p++; cout<<"Case "<<i<<':'<<endl; cout<<a<<" + "<<b<<" = "; if(c[clen]!=0) cout<<c[clen]; for(--clen;clen>=0;clen--) cout<<c[clen]; cout<<endl; } } return 0; }