题解 | #Powerful Calculator#
Powerful Calculator
https://www.nowcoder.com/practice/6bc1dd2ee0ce4257821531719b8d1c83
#include <iostream> #include <vector> using namespace std; vector<int> a,b,add_c, sub_c, mul_c; vector<int> add(vector<int> &a, vector<int> &b) { if(a.size() < b.size()) return add(b,a); int t = 0; for(int i = 0; i < a.size(); i++) { t += a[i]; if(i < b.size()) t += b[i]; add_c.push_back(t % 10); t /= 10; } if(t) add_c.push_back(t); return add_c; } bool cmp(vector<int> &a, vector<int> &b) { if(a.size() != b.size()) return a.size() > b.size(); for(int i = a.size() - 1; i >= 0; i--) if(a[i] != b[i]) return a[i] > b[i]; return true; } vector<int> sub(vector<int> &a, vector<int> &b) { int t = 0; for(int i = 0; i < a.size(); i++) { t = a[i] - t; if(i < b.size()) t -= b[i]; sub_c.push_back((t+10) % 10); if(t < 0) t = 1; else t = 0; } while(sub_c.size() > 1 && sub_c.back() == 0) sub_c.pop_back(); return sub_c; } vector<int> mul(vector<int> &a, vector<int> &b) { vector<int> mul_c(max(a.size(), b.size()) + 100, 0); for(int i = 0; i < a.size(); i++) { for(int j = 0; j < b.size(); j++) { mul_c[i+j] += a[i] * b[j]; } } for(int i = 0; i < mul_c.size(); i++) { mul_c[i+1] += mul_c[i] / 10; mul_c[i] %= 10; } while(mul_c.size() > 1 && mul_c.back() == 0) mul_c.pop_back(); return mul_c; } int main() { string m, n; cin >> m >> n; for(int i = m.size() - 1; i >= 0; i--) a.push_back(m[i] - '0'); for(int i = n.size() - 1; i >= 0; i--) b.push_back(n[i] - '0'); //加法 add_c = add(a,b); for(int i = add_c.size() - 1; i >= 0 ; i--) cout << add_c[i]; cout << endl; //减法 if(cmp(a, b)) sub_c = sub(a, b); else { sub_c = sub(b, a) ; cout << '-'; } for(int i = sub_c.size() - 1; i >= 0 ; i--) cout << sub_c[i]; cout << endl; //乘法 mul_c = mul(a, b); for(int i = mul_c.size() - 1; i >= 0 ; i--) cout << mul_c[i]; cout << endl; } // 64 位输出请用 printf("%lld")