title: 大数的加减乘除幂date: 2020-12-10 10:46
tags: C++
categories: 编程练习

+

  1. #include <iostream>
  2. #include <string>
  3. #include <stack>
  4. #include <algorithm> //reverse
  5. using namespace std;
  6. int main()
  7. {
  8. string a,b;
  9. stack<int>result;
  10. cin>>a>>b;
  11. int i = 0;
  12. int add = 0,t = 0;
  13. reverse(a.begin(),a.end()); //倒置字符串
  14. reverse(b.begin(),b.end());
  15. while(i < a.length() && i < b.length())
  16. {
  17. t = (a.at(i) + b.at(i) + add - 96);
  18. result.push(t%10);
  19. add = t/10;
  20. i++;
  21. }
  22. while(i < a.length())
  23. {
  24. t = (a.at(i) + add - 48);
  25. result.push(t%10);
  26. add = t/10;
  27. i++;
  28. }
  29. while(i < b.length())
  30. {
  31. t = (b.at(i) + add - 48);
  32. result.push(t%10);
  33. add = t/10;
  34. i++;
  35. }
  36. if(add) result.push(add);
  37. while(!result.empty())
  38. {
  39. cout<<result.top();
  40. result.pop();
  41. }
  42. cout<<"\nDone!"<<endl;
  43. return 0;
  44. }

*

  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. #include <algorithm>
  5. using namespace std;
  6. void add_string(string &r,string &a)
  7. {
  8. string st = r; //借助st实现result += temp
  9. r.clear(); //result清空
  10. int i = 0,add = 0,t;
  11. while(i < st.length() && i < a.length())
  12. {
  13. t = (st.at(i) + a.at(i) + add - 96);
  14. r += (t%10 +48);
  15. add = t/10;
  16. i++;
  17. }
  18. while(i < st.length())
  19. {
  20. t = (st.at(i) + add - 48);
  21. r += (t%10 +48);
  22. add = t/10;
  23. i++;
  24. }
  25. while(i < a.length())
  26. {
  27. t = (a.at(i) + add - 48);
  28. r += (t%10 +48);
  29. add = t/10;
  30. i++;
  31. }
  32. if(add) r += add+48;
  33. return;
  34. }
  35. int main()
  36. {
  37. //calculate
  38. string result;
  39. string temp;
  40. string a,b;
  41. cin >> a >> b;
  42. if(a.length() > b.length())
  43. {
  44. string t;
  45. t = a;
  46. a = b;
  47. b = t;
  48. } //a 作为乘法中的较小数
  49. reverse(a.begin(), a.end());
  50. reverse(b.begin(),b.end());
  51. int i = 0,j= 0,t = 0;
  52. int add = 0;
  53. int flag;
  54. while (i < a.length())
  55. {
  56. flag = i;
  57. while(flag--) temp += '0';
  58. for(j = 0; j < b.length(); j++)
  59. {
  60. t = (a.at(i)-48) * (b.at(j)-48) + add;
  61. temp += (t%10 + 48);
  62. add = t/10;
  63. }
  64. if(add) temp += add+48;
  65. add = 0;
  66. add_string(result,temp);
  67. temp.clear();
  68. i++;
  69. }
  70. stack <int> st;
  71. for(i = 0;i < result.length();i++)
  72. {
  73. st.push(result.at(i) - 48);
  74. }
  75. while(!st.empty())
  76. {
  77. cout<<st.top();
  78. st.pop();
  79. }
  80. cout << "\nDone" << endl;
  81. return 0;
  82. }