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

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

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

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

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

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

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

完整的实现代码如下:

#include "iostream"

#include "stack"

using namespace std;

stacks1;

stacks2;

stacks3;

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

{

s1.push(c1[i]-'0'); //按输入顺序(高位到低位)入栈1,此时栈顶为最低位

}

for(int i=0;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.pop();

}

cout<

system("pause");

return 0;

}

#include "iostream"

#include "stack"

using namespace std;

stacks1;

stacks2;

stacks3;

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

{

s1.push(c1[i]-'0'); //按输入顺序(高位到低位)入栈1,此时栈顶为最低位

}

for(int i=0;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.pop();

}

cout<

system("pause");

return 0;

}

1340358104_5525.png

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-06-22 17:37

浏览 712

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值