UVa10035 Primary Arithmetic
解説
二項加算の繰上げ回数を調べる。加算処理は string よりも vector
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; int main() { string a, b; while(cin >> a >> b) { if(a == "0" && b == "0") break; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); vector<int> A(20), B(20); for(int i=0; i<a.size(); i++) { A[i] = a[i] - '0'; } for(int i=0; i<b.size(); i++) { B[i] = b[i] - '0'; } int ans = 0; vector<int> RET(20); for(int i=0; i<15; i++) { int sum = A[i]+B[i]+RET[i]; RET[i] += sum % 10; while(sum > 9) { RET[i+1] ++; sum -= 10; ans ++; } } if(ans == 0) { cout << "No carry operation.\n"; } else if(ans == 1) { cout << "1 carry operation.\n"; } else { cout << ans << " carry operations.\n"; } } return 0; }