题解 | #Primary Arithmetic#
Primary Arithmetic
https://www.nowcoder.com/practice/c1fb44e931394e6693671f49c899f5de
所有的情况行云流水,还考虑到了两个数的位数不同的情况,供大家参考。
#include<cstdio> #include<stack> #include<vector> #include<string> using namespace std; int main() { char arr1[10]; char arr2[10]; while (scanf("%s %s", arr1, arr2) != EOF) { string s1 = arr1; string s2 = arr2; if (s1 == "0" && s1 == "0") { break; } int len1 = s1.size(); int len2 = s2.size(); stack<int> sta1; stack<int> sta2; for (int i = 0 ; i < len1 ; ++i ) { sta1.push(s1[i] - '0'); } for (int i = 0 ; i < len2 ; ++i ) { sta2.push(s2[i] - '0'); } vector<int> vec1; vector<int> vec2; for (int i = 0 ; i < len1 ; ++i) { vec1.push_back(sta1.top()); sta1.pop(); } for (int i = 0 ; i < len2 ; ++i) { vec2.push_back(sta2.top()); sta2.pop(); } int count = 0 ; int carry =0; for (int i = 0 ; i < len1 && i < len2; ++i) { if (vec1[i] + vec2[i] + carry>= 10) { ++count; carry =1; } else { carry = 0; } } if (count == 0) { printf("NO carry operation.\n"); } else if (count == 1) { printf("%d carry operation.\n", count); } else { printf("%d carry operations.\n", count); } } return 0; }