我以前问过这个问题,但方式比较复杂,我想可能我不太清楚。
假设我有两个整数堆栈,每个代表一个整数,从字符串中解析。第一个是1的位置,第二个是10的位置,第三个是100的位置,等等。我很难把我的头绕在这上面,因为我觉得我需要递归地做它,递归算法让我困惑,特别是在这种情况下。我很感激你的帮助。
int difference, z;
for (i = 0; i < length; i++)
{
x = firstNum.pop();
y = secondNum.pop();
difference = x - y;
if (difference < 0)
{
z = firstNum.pop();
firstNum.push(z - 1);
firstNum.push(x + 10);
}
else
{
result.push(difference);
}
}
最佳答案
不需要递归,但有一个错误。
int difference, z;
while (!firstNum.isEmpty ())
{
x = firstNum.pop();
y = 0;
if (!secondNum.isEmpty ()) // account for the case when secondNum has less digits
y = secondNum.pop();
difference = x - y;
if (difference < 0)
{
z = firstNum.pop();
firstNum.push(z - 1);
result.push(difference + 10); // fixed this line, since you want to push the
// difference to the result
}
else
{
result.push(difference);
}
}
现在,您应该注意到
result
堆栈中的数字将按相反的顺序排列。减法结束时,最有意义的数字将位于堆栈的顶部。下面是一个完整的硬编码样本输入方法:
public static void subtract ()
{
Stack<Integer> firstNum = new Stack<Integer>();
Stack<Integer> secondNum = new Stack<Integer>();
Stack<Integer> result = new Stack<Integer>();
// firstNum == 3002
firstNum.push (3);
firstNum.push (0);
firstNum.push (0);
firstNum.push (2);
// secondNum == 129
secondNum.push (1);
secondNum.push (2);
secondNum.push (9);
int difference, z;
while (!firstNum.isEmpty ())
{
int x = firstNum.pop();
int y = 0;
if (!secondNum.isEmpty ())
y = secondNum.pop();
difference = x - y;
if (difference < 0)
{
z = firstNum.pop();
firstNum.push(z - 1);
result.push(difference + 10);
}
else
{
result.push(difference);
}
}
while (!result.isEmpty ())
System.out.print (result.pop ());
System.out.println ();
}
输出
2873
注意,此方法假设第一个数字高于第二个数字。对于第一个数字较小的情况,应添加一些处理。