微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

大数相加的C++简单实现

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void addsum(vector<int>v1,vector<int>v2)
{
	int size1=v1.size(),size2=v2.size();
	vector<int>vvs;
	int y=size1-1;
	for (int k=size2-1;k>=0;k--,y--)
	{
		int ssum;
		ssum=v1[y]+v2[k];
		if (ssum>=10)
		{
			vvs.push_back(ssum%10);
			v1[y-1]+=ssum/10;
		}
		else
		{
			vvs.push_back(ssum);
		}
	}
		for (int l=size1-size2-1;l>=0;l--)
		{
			if (v1[l]>=10)
			{
				if (l!=0)
				{
					v1[l-1]+=v1[l]/10;
					vvs.push_back(v1[l]%10);
				}
				else
				{
					vvs.push_back(v1[l]%10);
					vvs.push_back(v1[l]/10);
				}
			}
			else
			{
				vvs.push_back(v1[l]);
			}
		}
	vector<int>result;
	vector<int>::reverse_iterator ri=vvs.rbegin();
	for (;ri!=vvs.rend();ri++)
	{
	    result.push_back(*ri);
	}
	vector<int>::iterator it=result.begin();
	while(it!=result.end())
	{
		cout<<*it;
		++it;
	}
	cout<<endl;
}
void sum(string s1,string s2)
{
	vector<int>vi1,vi2;
	int size1=s1.size();
	int size2=s2.size();
	for (int i=0;i<size1;i++)
	{
		vi1.push_back(s1[i]-'0');
	}
	for (int j=0;j<size2;j++)
	{
		vi2.push_back(s2[j]-'0');
	}
	vector<int>vs;
	if (size1==size2)
	{
		for (int k=size1-1;k>=0;k--)
		{
			int sum;
			sum=vi1[k]+vi2[k];
			if (vi1[k]+vi2[k]>=10)
			{
				if (k!=0)
				{
					vi1[k-1]+=sum/10;
					vs.push_back(sum%10);
				}
				else
				{
					vs.push_back(sum%10);
					vs.push_back(sum/10);
				}
			}
			else
			{
				vs.push_back(sum);
			}
		}
	}
	vector<int>rresult;
	vector<int>::reverse_iterator rii=vs.rbegin();
	for (;rii!=vs.rend();rii++)
	{
		rresult.push_back(*rii);
	}
	vector<int>::iterator iit=rresult.begin();
	while(iit!=rresult.end())
	{
		cout<<*iit;
		++iit;
	}
	cout<<endl;
	if (size1>size2)
	{
		addsum(vi1,vi2);
	}
	if (size1<size2)
	{
		addsum(vi2,vi1);
	}
}
int main()
{
	string v1,v2;
	cin>>v1>>v2;
	sum(v1,v2);
	return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐