大整数加法
来源:互联网 发布:设计师导航源码 编辑:程序博客网 时间:2024/05/04 10:47
步骤: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;
- }
运行效果图如下:
转自:http://blog.csdn.net/hackbuteer1/article/details/6709101
// addMethord.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stack>
#include "iostream"
using namespace std;
stack<int> s1;
stack<int> s2;
stack<int> s3;
char c1[9000000000];
char c2[9000000000];
int main(int argc, char* argv[])
{
printf("input first !\n");
cin >> c1;
printf("input second !\n");
cin >> c2;
int len1 = strlen(c1);
int len2 = strlen(c2);
printf("len1 = %d\n", len1);
printf("len2 = %d\n", len2);
for (int i = 0; i < len1; i++) {
s1.push(c1[i] - '0');
}
for (int j = 0; j < len2; j++) {
s2.push(c2[j] - '0');
}
int tmp = 0;
while(!s1.empty() && !s2.empty()) {
tmp += s1.top() + s2.top();
s1.pop();
s2.pop();
s3.push(tmp % 10);
tmp = tmp / 10;
}
while(!s1.empty()) {
tmp += s1.top();
s1.pop();
s3.push(tmp % 10);
tmp = tmp / 10;
}
while(!s2.empty()) {
tmp += s2.top();
s2.pop();
s3.push(tmp % 10);
tmp = tmp / 10;
}
if(tmp) {
s3.push(tmp);
}
printf("The result length = %d\n", s3.size());
printf("The add result = ");
while(!s3.empty()) {
cout << s3.top();
s3.pop();
}
cout << endl;
system("pause");
return 0;
}
- 大整数加法
- 大整数加法
- 高精度 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法计算
- zoj1292大整数加法
- 大整数加法
- 大整数加法
- 大整数加法函数
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 大整数加法
- 【算法】大整数加法
- C++Builder 的一些高级编程技巧
- VirtualAlloc函数使用总结
- HDU 4048 Zhuge Liang's Stone Sentinel Maze
- 手机移动视频监控系统方案
- 《花开半夏》--4 生死之间的吻(1)
- 大整数加法
- UML图的绘制
- Maven多模块布局实例详解
- 设置Linux环境变量的三种方法
- nm命令介绍
- 初识.Net appconfig
- 谈谈如何增强用户体验的愉悦感
- 当我遇到项目需要优化时
- 2010中可以使用的donetbar