如何使用堆栈添加大数?
class LargeNumberPb
{
Stack s1;
Stack s2;
Stack res;
string first;
string second;
public LargeNumberPb()
{
first = "10";
second = "11";
s1 = new Stack();
s2 = new Stack();
res = new Stack();
}
public void Fill()
{
for (int i = 0; i < first.Length; i++)
{
s1.Push(first.Substring(i,1));
}
for (int i = 0; i < second.Length; i++)
{
s2.Push(second.Substring(i,1));
}
}
public Stack Sum()
{
for (int i = 0; i < s.Count; i++)
{
res.Push(Convert.ToInt32(s1.Pop()) + Convert.ToInt32(s2.Pop()));
}
return res;
}
}
我想使用堆栈解决添加大量数字的问题。但它没有以正确的方式工作,如果两个数字是 100 和 11,那么进位会去哪里?
class LargeNumberPb
{
Stack s1;
Stack s2;
Stack res;
string first;
string second;
public LargeNumberPb()
{
first = "10";
second = "11";
s1 = new Stack();
s2 = new Stack();
res = new Stack();
}
public void Fill()
{
for (int i = 0; i < first.Length; i++)
{
s1.Push(first.Substring(i,1));
}
for (int i = 0; i < second.Length; i++)
{
s2.Push(second.Substring(i,1));
}
}
public Stack Sum()
{
for (int i = 0; i < s.Count; i++)
{
res.Push(Convert.ToInt32(s1.Pop()) + Convert.ToInt32(s2.Pop()));
}
return res;
}
}
I want to solve adding large number problem, using stack. but it is not working in a right way, if two numbers are 100 and 11, then where the carry will go?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果两个数字具有相同的位数,只需修复您的求和函数(仅处理进位,代码未测试):
编辑: 这是不同长度字符串的编辑版本:
If two numbers have equal digit count just fix your sum function (just handle carry, code is not tested):
Edit: and this is a edited version for different length strings:
您只需要一个变量即可继续。当您从 stak 中弹出数字并将其相加时,如果有进位,则将该值分配给您拥有的额外变量。这就是你真正需要的。
You need only one variable for carry on. While you are popping numbers from staks and adding them, if there is a carry on, you assign that value to extra variable you have. That s all you need really.