`
java-mans
  • 浏览: 11343079 次
文章分类
社区版块
存档分类
最新评论

任意长度的高精度大整数加法

 
阅读更多
方法:这里用了数据结构栈,实际上栈更方便实现高精度加法。

步骤:1、第一个数据加数按输入顺序(高位到低位)入栈1。此时栈顶为最低位

2、‍第二个数据加数按输入顺序(高位到低位)入栈2。此时栈顶为最低位

3、将栈1、栈2均pop出栈顶做加法,并考虑进位,结果入栈3,这时栈3正好是低位入栈。

4、处理多余的栈1、栈2。

5、直接pop出栈3,即正好的从高位到低位的结果。

完整的实现代码如下:

#include "iostream"
#include "stack"
using namespace std;

stack<int>s1;
stack<int>s2;
stack<int>s3;
char c1[100];
char c2[100];

int main(void)
{
printf("请输入第一个加数:");
cin>>c1;
printf("请输入第二个加数:");
cin>>c2;
int len1=strlen(c1);
int len2=strlen(c2);
for(int i=0;i<len1;i++)
{
s1.push(c1[i]-'0'); //按输入顺序(高位到低位)入栈1,此时栈顶为最低位
}
for(int i=0;i<len2;i++)
{
s2.push(c2[i]-'0'); //按输入顺序(高位到低位)入栈2,此时栈顶为最低位
}

int tmp=0;
while(!s1.empty() && !s2.empty())
{
tmp += s1.top()+s2.top(); // 将栈1、栈2均pop出栈顶做加法,并考虑进位,结果入栈3,这时栈3正好是低位入栈
s1.pop();
s2.pop();
s3.push(tmp%10);
tmp = tmp/10;
}
while(!s1.empty()) //处理多余的栈1
{
tmp += s1.top();
s1.pop();
s3.push(tmp%10);
tmp = tmp/10;
}
while(!s2.empty()) //处理多余的栈2
{
tmp += s2.top();
s2.pop();
s3.push(tmp%10);
tmp = tmp/10;
}
if(tmp) //处理多余的进位
{
s3.push(tmp);
}

printf("两个数相加的结果为:");
while(!s3.empty()) //直接pop出栈3,即正好的从高位到低位的结果
{
cout<<s3.top();
s3.pop();
}
cout<<endl;
system("pause");
return 0;
}

#include "iostream"
#include "stack"
using namespace std;

stack<int>s1;
stack<int>s2;
stack<int>s3;
char c1[100];
char c2[100];

int main(void)
{
	printf("请输入第一个加数:");
	cin>>c1;
	printf("请输入第二个加数:");
	cin>>c2;
	int len1=strlen(c1);
	int len2=strlen(c2);
	for(int i=0;i<len1;i++)
	{
		s1.push(c1[i]-'0');            //按输入顺序(高位到低位)入栈1,此时栈顶为最低位
	}
	for(int i=0;i<len2;i++)
	{
		s2.push(c2[i]-'0');            //按输入顺序(高位到低位)入栈2,此时栈顶为最低位
	}

	int tmp=0;
	while(!s1.empty() && !s2.empty())
	{
		tmp += s1.top()+s2.top();   // 将栈1、栈2均pop出栈顶做加法,并考虑进位,结果入栈3,这时栈3正好是低位入栈
		s1.pop();
		s2.pop();
		s3.push(tmp%10);
		tmp = tmp/10;
	}
	while(!s1.empty())   //处理多余的栈1
	{
		tmp += s1.top();
		s1.pop();
		s3.push(tmp%10);
		tmp = tmp/10;
	}
	while(!s2.empty())   //处理多余的栈2
	{
		tmp += s2.top();
		s2.pop();
		s3.push(tmp%10);
		tmp = tmp/10;
	}
	if(tmp)        //处理多余的进位
	{
		s3.push(tmp);
	}

	printf("两个数相加的结果为:");
	while(!s3.empty())    //直接pop出栈3,即正好的从高位到低位的结果
	{
		cout<<s3.top();
		s3.pop();
	}
	cout<<endl;
	system("pause");
	return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics