摘要
题目链接 |
难度等级 |
完成状态 |
完成分数 |
最后编辑时间 |
失误原因(初次提交分数)
|
高精度练习之加法
|
★☆☆☆☆
|
答案正确
|
100
|
2014-10-11 21:26:36
|
输出格式(60)
|
题意
500位以内的加法。
题解
一位一位加,加完进位,类似于小学列竖式的方法。优化一些的常常使用万进制加法。
可以建立对象,通过重载运算符来使得程序更美观。
- 返回值类型 operator 符号 (参数a,参数b){...};
- //栗子:
- largeInt operator +(largeInt lhs,largeInt rhs){...};
然后可以于对象内部建立friend函数,以便访问私有函数。在对象内部建议用friend写法取代另一种operator的写法:
- class T
- {
- T operator +(T rhs){...} //不推荐的写法
- friend T operator +(T lhs,T rhs){...} //推荐的写法
- }
原因是如果涉及隐式类型转换,下面那一种可以正确处理而上面只能处理右值。
其它不多说了。
代码
3116.cpp代码已折叠
展开折叠内容
|
- #include<iostream>
- #include<iomanip>
- #include<algorithm>
- #include<vector>
- using namespace std;
- class largeInt
- {
- public:
- const int size() const
- {
- return u.size();
- }
- largeInt()
- {
- u.clear();
- u.push_back(0);
- }
- largeInt(const int &number)
- {
- u.clear();
- u.push_back(number);
- carry();
- }
- void scan()
- {
- u.clear();
- string original;
- cin>>original;
- for(int i=original.size()-1,j=0,p=1;i>=0;--i)
- {
- j+=(original[i]-'0')*p;
- p*=10;
- if((!i) || p==10000)
- {
- u.push_back(j);
- j=0;
- p=1;
- }
- }
- }
- void print() const
- {
- cout<<setw(0)<<setfill('0')<<u[size()-1];
- for(int i=size()-2;i>=0;--i)
- cout<<setw(4)<<setfill('0')<<u[i];
- }
- friend const largeInt operator +(const largeInt &a,const largeInt &b)
- {
- largeInt r;
- r.u.resize(max(a.size(),b.size()));
- for(int i=0;i<r.size();++i)
- {
- if(i<a.size())
- r.u[i]+=a.u[i];
- if(i<b.size())
- r.u[i]+=b.u[i];
- }
- r.carry();
- return r;
- }
- private:
- vector<int> u;
- void carry()
- {
- for(int i=0;i<size();++i)
- {
- if(u[i]>=10000)
- {
- if(i==size()-1)
- u.push_back(u[i]/10000);
- else
- u[i+1]+=u[i]/10000;
- u[i]%=10000;
- }
- }
- }
- };
- int main()
- {
- largeInt a,b;
- a.scan();
- b.scan();
- (a+b).print();
- }
|