题解 | #Powerful Calculator#
Powerful Calculator
https://www.nowcoder.com/practice/6bc1dd2ee0ce4257821531719b8d1c83
#include <iostream> #include <vector> using namespace std; void print(vector<int> &res){ for(int i=res.size()-1;i>=0;i--) cout<<res[i]; cout<<endl; } vector<int> add(vector<int> &A,vector<int> &B){ int t=0; vector<int> C; for(int i=0;i<A.size()||i<B.size();i++){ if(i<A.size()) t+=A[i]; if(i<B.size()) t+=B[i]; C.push_back(t%10); t/=10; } if(t) C.push_back(t); return C;//个十百千万... } //判断A>=B? 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;//A==B } vector<int> sub(vector<int> &A,vector<int> &B){ int t=0;//向高位借位 vector<int> C; for(int i=0;i<A.size();i++){ t=A[i]-t; if(i<B.size()) t-=B[i]; C.push_back((t+10)%10); if(t<0) t=1; else t=0; } //去除前导零 while(C.size()>1&&C.back()==0) C.pop_back(); return C; } vector<int> mul(vector<int> &A,vector<int> &B){ vector<int> C(A.size()+B.size(),0); for(int i=0;i<A.size();i++){ for(int j=0;j<B.size();j++){ C[i+j]+=A[i]*B[j]; } } for(int i=0;i+1<C.size();i++){ C[i+1]+=C[i]/10; C[i]%=10; } //去除前导零 while(C.size()>1&&C.back()==0) C.pop_back(); return C; } int main() { string a,b; while(cin>>a>>b){ vector<int> A,B; for(int i=a.size()-1;i>=0;i--) A.push_back(a[i]-'0');//个十百千万... for(int i=b.size()-1;i>=0;i--) B.push_back(b[i]-'0'); vector<int> res; res=add(A,B); print(res); if(cmp(A,B)){ res=sub(A,B); }else{ cout<<"-"; res=sub(B,A); } print(res); res=mul(A,B); print(res); } return 0; }