高精计算
编写一个以字符串为基础进行整数加法的一个程序。这个整数包含符号位,总长不超过255位(因为某些语言的字符串有长度限制)。
输入文件格式:两行,每行为一个长度不超过255的十进制数。可以是负的,负号算一位,既负数的数字部分不超过254位。
in.txt
输出文件格式:一行,得数。
out.txt
#include
<
fstream
>
#include
<
vector
>
#include
<
string
>
#include
<
iostream
>
using
namespace
std;
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
int
main()
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
...
{
ifstream infile("in.txt");
ofstream outfile("out.txt");
string s1,s2;
getline(infile,s1);
getline(infile,s2);
string::iterator s_iter1(s1.begin()),s_iter2(s2.begin());
int len,sign1(1),sign2(1),sign_ans(1);
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
if (*s_iter1=='-')...{
sign1=-1;
s1.erase(s_iter1);
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
if (*s_iter2=='-')...{
sign2=-1;
s2.erase(s_iter2);
}
if (s1.size()>s2.size())
len=s1.size();
else
len=s2.size();
vector<int> ans(len+1,0),ivec1(len,0),ivec2(len,0);
vector<int>::reverse_iterator r_iter1(ivec1.rbegin()+len-s1.size()),r_iter2(ivec2.rbegin()+len-s2.size()),r_iter_ans(ans.rbegin());
vector<int>::iterator iter1(ivec1.begin()),iter2(ivec2.begin()),iter_ans(ans.begin());
if (sign1==1)
for (int i=0;i!=s1.size();++i,++r_iter1)
*r_iter1=s1[i]-'0';
else
for (int i=0;i!=s1.size();++i,++r_iter1)
*r_iter1='0'-s1[i];
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
if (sign2==1)
for (int i=0;i!=s2.size();++i,++r_iter2)
*r_iter2=s2[i]-'0';
else
for (int i=0;i!=s2.size();++i,++r_iter2)
*r_iter2='0'-s2[i];
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
for (int i=0;i!=len;++i,++iter1,++iter2,++iter_ans)
*iter_ans=*iter1+*iter2;
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
if (*(iter_ans-1)<0)...{
outfile<<"-";
iter_ans=ans.begin();
for (int i=0;i!=len;++iter_ans,++i)
*iter_ans=-*iter_ans;
}
iter_ans=ans.begin();
for (int i=0;i!=len;++iter_ans,++i)
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
if (*iter_ans>0)...{
*(iter_ans+1)+=*iter_ans/10;
*iter_ans=*iter_ans%10;
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
else if (*iter_ans!=0)...{
--*(iter_ans+1);
*iter_ans+=10;
}
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
for (;r_iter_ans!=ans.rend();++r_iter_ans)
if ((sign_ans==1)&&(*r_iter_ans==0))
continue;
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
else...{
sign_ans=0;
outfile<<*r_iter_ans;
}
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
infile.close();
outfile.close();
return 0;
}