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;
}
}
我想用stack来解决添加大数的问题。但它的工作方式不对,如果两个数字是100和11,那么进位会去哪里?
最佳答案
如果两个数字的位数相等,只需修复sum函数(只处理进位,不测试代码):
public Stack Sum()
{
int carry = 0;
int count = s1.Count;
for (int i = 0; i < count; i++)
{
var result = Convert.ToInt32(s1.Pop()) + Convert.ToInt32(s2.Pop())
+ carry;
res.Push(result%10);
carry = (result - result % 10)/10;
}
var carryStream = carry.ToString();
for(int i=carryStream.Length-1;i>=0;i--)
{
res.push(Convert.ToInt32(carryStream.Substring(i,1);
}
return res;
}
编辑:这是不同长度字符串的编辑版本:
public Stack Sum()
{
int carry = 0;
int count = Math.Min(s1.Count, s2.Count);
for (int i = 0; i < count; i++)
{
var result = Convert.ToInt32(s1.Pop()) + Convert.ToInt32(s2.Pop())
+ carry;
res.Push(result % 10);
carry = (result - result % 10) / 10;
}
var carryStream = carry.ToString();
var remainedStack = s1.Count > 0 ? s1 : s2;
carry = 0;
for (int i = carryStream.Length - 1; i >= 0; i--)
{
var result = Convert.ToInt32(carryStream.Substring(i, 1))
+ (remainedStack.Count > 0 ? Convert.ToInt32(remainedStack.Pop()) : 0);
res.Push(result % 10);
carry = (result - result % 10) / 10;
}
if (remainedStack.Count > 0)
{
int remainedCount = remainedStack.Count;
for (int i = 0; i < remainedStack.Count; i++)
{
var result = carry + Convert.ToInt32(remainedStack.Pop());
res.Push(result % 10);
carry = (result - result % 10) / 10;
}
}
if (carry != 0)
res.Push(carry);
return res;
}
关于c# - 如何用堆栈增加大数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7879158/