题目大意:
http://codevs.cn/problem/3116/
题解:
#include <iostream> #include <string> #include <cstring> #include <sstream> #define trans(x)(x-'0') using namespace std; string trans2(int i) { stringstream s; s << i; string ss; s >> ss; return ss; } int main() { string s1,s2; cin >> s1 >> s2; int l1 = s1.length(); int l2 = s2.length(); if(l1 < l2){ string tmp = s2; s2 = s1; s1 = tmp; } l1 = s1.length(); l2 = s2.length(); string str; int flag = 0; int j = l1-1; for(int i = l2-1; i >= 0; i--,j--) { if(trans(s2[i])+trans(s1[j]) >= 10) { int result = (trans((s2[i])+trans(s1[j]))) % 10 + flag; flag = 1; str.insert(0,trans2(result)); } else if(trans(s2[i])+trans(s1[j]) + flag >= 10) { int result = 0; flag = 1; str.insert(0,trans2(result)); } else { int result = trans((s2[i])+trans(s1[j])) + flag; flag = 0; str.insert(0,trans2(result)); } } for(int i = j; i >= 0; i-- ) { if(trans(s1[i])+flag >= 10) { int result = (trans(s1[i])+flag) % 10; flag = 1; str.insert(0,trans2(result)); } else { int result = (trans(s1[i])+flag); flag = 0; str.insert(0,trans2(result)); } } if(flag == 1) str = '1' + str; cout << str << endl; return 0; }
之前写的太麻烦,给个新的:
#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; char a[501]; char b[501]; int res[501]; int add(char a[], char b[]) { int la = strlen(a) - 1; int lb = strlen(b) - 1; int tmp = 0; int flag = 0; while(la >= 0) { int aa = a[la] - '0'; int bb = (lb >= 0)? b[lb] - '0' : 0; res[tmp++] = (aa + bb + flag) < 10 ? aa+bb+flag : (aa+bb+flag)%10; flag = (aa + bb + flag) / 10; la--; lb--; } if(flag == 1){ res[tmp++] = 1; } return tmp; } int main() { cin >> a >> b; int la = strlen(a); int lb = strlen(b); int count = 0; if(la > lb) count = add(a,b); else count = add(b,a); for(int i = count-1; i >= 0; i--) cout << res[i]; cout << endl; return 0; }