title: 大数的加减乘除幂date: 2020-12-10 10:46
tags: C++
categories: 编程练习
+
#include <iostream>#include <string>#include <stack>#include <algorithm> //reverseusing namespace std;int main(){ string a,b; stack<int>result; cin>>a>>b; int i = 0; int add = 0,t = 0; reverse(a.begin(),a.end()); //倒置字符串 reverse(b.begin(),b.end()); while(i < a.length() && i < b.length()) { t = (a.at(i) + b.at(i) + add - 96); result.push(t%10); add = t/10; i++; } while(i < a.length()) { t = (a.at(i) + add - 48); result.push(t%10); add = t/10; i++; } while(i < b.length()) { t = (b.at(i) + add - 48); result.push(t%10); add = t/10; i++; } if(add) result.push(add); while(!result.empty()) { cout<<result.top(); result.pop(); } cout<<"\nDone!"<<endl; return 0;}
*
#include <iostream>#include <stack>#include <string>#include <algorithm>using namespace std;void add_string(string &r,string &a){ string st = r; //借助st实现result += temp r.clear(); //result清空 int i = 0,add = 0,t; while(i < st.length() && i < a.length()) { t = (st.at(i) + a.at(i) + add - 96); r += (t%10 +48); add = t/10; i++; } while(i < st.length()) { t = (st.at(i) + add - 48); r += (t%10 +48); add = t/10; i++; } while(i < a.length()) { t = (a.at(i) + add - 48); r += (t%10 +48); add = t/10; i++; } if(add) r += add+48; return;}int main(){ //calculate string result; string temp; string a,b; cin >> a >> b; if(a.length() > b.length()) { string t; t = a; a = b; b = t; } //a 作为乘法中的较小数 reverse(a.begin(), a.end()); reverse(b.begin(),b.end()); int i = 0,j= 0,t = 0; int add = 0; int flag; while (i < a.length()) { flag = i; while(flag--) temp += '0'; for(j = 0; j < b.length(); j++) { t = (a.at(i)-48) * (b.at(j)-48) + add; temp += (t%10 + 48); add = t/10; } if(add) temp += add+48; add = 0; add_string(result,temp); temp.clear(); i++; } stack <int> st; for(i = 0;i < result.length();i++) { st.push(result.at(i) - 48); } while(!st.empty()) { cout<<st.top(); st.pop(); } cout << "\nDone" << endl; return 0;}