任意长度的高精度大整数加法
来源:互联网 发布:小土豆编程破解版 编辑:程序博客网 时间: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;}
- 任意长度的高精度大整数加法
- 任意长度的高精度大整数加法
- 任意长度的高精度大整数加法
- 任意长度的高精度大整数和浮点数的加法和乘法
- 高精度 大整数加法
- 高精度大整数加法
- 高精度整数加法(大整数加法)
- 高精度(大整数加法)
- 任意长度的整数加法C语言代码
- 经典算法11:任意长度整数加法
- 两个大整数相加—高精度加法
- c语言高精度大整数加法运算
- 【高精度计算 01】 大整数加法
- poj 1503 大整数高精度 加法
- 任意长度数字的加法
- 大整数的加法
- 大整数的加法
- 大整数的加法
- 阿里云2011.9.17招聘会笔试题
- Android竖排显示文字
- hextoraw函数和rawtohex函数
- Centos 下安装 subversion
- abort
- 任意长度的高精度大整数加法
- GOT(全局偏移表)和PLT(过程链接表)
- Android 标题栏、状态栏隐藏
- 敏捷开发“松结对编程”实践之四:日常工作篇(大型研发团队,学习型团队,139团队,师徒制度,检查点,代码审查,每日立会)
- Android 开发之使用Eclipse Debug调试详解
- Request method 'GET' not supported
- php调用matlab
- Excel文件与DataSet之间的转化的探索与实现
- 磁盘检测的作用以及相关操作