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

来源:互联网 发布:小土豆编程破解版 编辑:程序博客网 时间:2024/05/02 00:13
方法:这里用了数据结构栈,实际上栈更方便实现高精度加法。

步骤: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;}


 

 

 

原创粉丝点击