摘要

题目链接 难度等级 完成状态 完成分数 最后编辑时间 失误原因(初次提交分数)
高精度练习之加法 ★☆☆☆☆ 答案正确 100 2014-10-11 21:26:36 输出格式(60)

题意

500位以内的加法。

题解

一位一位加,加完进位,类似于小学列竖式的方法。优化一些的常常使用万进制加法。

可以建立对象,通过重载运算符来使得程序更美观。

显示/移除行号
  1. 返回值类型 operator 符号 (参数a,参数b){...};
  2. //栗子:
  3. largeInt operator +(largeInt lhs,largeInt rhs){...};

然后可以于对象内部建立friend函数,以便访问私有函数。在对象内部建议用friend写法取代另一种operator的写法:

显示/移除行号
  1. class T
  2. {
  3. T operator +(T rhs){...} //不推荐的写法
  4. friend T operator +(T lhs,T rhs){...} //推荐的写法
  5. }

原因是如果涉及隐式类型转换,下面那一种可以正确处理而上面只能处理右值。

其它不多说了。

代码

3116.cpp代码已折叠
展开折叠内容
显示/移除行号
  1. #include<iostream>
  2. #include<iomanip>
  3. #include<algorithm>
  4. #include<vector>
  5. using namespace std;
  6. class largeInt
  7. {
  8. public:
  9. const int size() const
  10. {
  11. return u.size();
  12. }
  13. largeInt()
  14. {
  15. u.clear();
  16. u.push_back(0);
  17. }
  18. largeInt(const int &number)
  19. {
  20. u.clear();
  21. u.push_back(number);
  22. carry();
  23. }
  24. void scan()
  25. {
  26. u.clear();
  27. string original;
  28. cin>>original;
  29. for(int i=original.size()-1,j=0,p=1;i>=0;--i)
  30. {
  31. j+=(original[i]-'0')*p;
  32. p*=10;
  33. if((!i) || p==10000)
  34. {
  35. u.push_back(j);
  36. j=0;
  37. p=1;
  38. }
  39. }
  40. }
  41. void print() const
  42. {
  43. cout<<setw(0)<<setfill('0')<<u[size()-1];
  44. for(int i=size()-2;i>=0;--i)
  45. cout<<setw(4)<<setfill('0')<<u[i];
  46. }
  47. friend const largeInt operator +(const largeInt &a,const largeInt &b)
  48. {
  49. largeInt r;
  50. r.u.resize(max(a.size(),b.size()));
  51. for(int i=0;i<r.size();++i)
  52. {
  53. if(i<a.size())
  54. r.u[i]+=a.u[i];
  55. if(i<b.size())
  56. r.u[i]+=b.u[i];
  57. }
  58. r.carry();
  59. return r;
  60. }
  61. private:
  62. vector<int> u;
  63. void carry()
  64. {
  65. for(int i=0;i<size();++i)
  66. {
  67. if(u[i]>=10000)
  68. {
  69. if(i==size()-1)
  70. u.push_back(u[i]/10000);
  71. else
  72. u[i+1]+=u[i]/10000;
  73. u[i]%=10000;
  74. }
  75. }
  76. }
  77. };
  78. int main()
  79. {
  80. largeInt a,b;
  81. a.scan();
  82. b.scan();
  83. (a+b).print();
  84. }

著作权声明[编辑]

关于[编辑]