我添加了兩個非常大的整數,最多125位數字,不使用Integer類或BigInteger類,只使用java的Stack實用程序。它只是將兩個大整數加載到一個堆棧中,然後比較每個pop()
。堆棧行爲與數學
我最初具有加載棧,A的方法和B從自己JTextArea.getText()
public Stack<Integer> loadStack(String numA)
{
Scanner scan = new Scanner(numA);
Stack<Integer> stack = new Stack<Integer>();
while (scan.hasNext())
{
stack.push(scan.nextInt());
}
//System.out.println(stack.toString());
return stack;
}
,然後我的方法,其顯示所得疊層被稱爲resTF.setText(num.addStacks(stackA, stackB).toString());
其中resTF是另一個的JTextArea爲的結果。
我的方法,增加了帶兩個Stack<Integer>
的
public Stack<Integer> addStacks(Stack<Integer> stackA, Stack<Integer> stackB)
{
Stack<Integer> resultStack = new Stack<Integer>();
while(!stackA.empty() && !stackB.empty())
{
try
{
int carry = 0;
//get the digits to add
int tokenA = stackA.pop();
int tokenB = stackB.pop();
//add them and mod 10
int result = tokenA + tokenB + carry;
int resultDigit = result % 10;
//push the result on to the new stack
resultStack.push(resultDigit);
//the updated carry
carry = result/10;
if (carry > 0)
{
resultStack.push(carry);
}
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
System.out.println(resultStack.toString());
return resultStack;
}
1:我的籌碼是給我的輸出,例如,[6, 66]
加入555
和111
時,當所需的輸出將[6,6,6]
我覺得呢?爲什麼是這樣?因爲它被讀入的方式?我相信我可能會加入其中。當我輸入非常非常大的數字,如100000000000000000000000000000000000000
和200000000000000000000000000000000000000
我得到了,所以我知道它的loadStacks方法是導致問題的原因,尤其是掃描它。我缺少什麼?
Exception in thread "AWT-EventQueue-0" java.util.InputMismatchException: For input string: "100000000000000000000000000000000000000"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at GUI.BigNumber.loadStack(BigNumber.java:19)
EDIT 1 *****
public void checkJagged(Stack<Integer> stackA, Stack<Integer> stackB)
{
int stackSizeA = stackA.size();
int stackSizeB = stackB.size();
if (stackA.size() < stackB.size())
{
for (int i = 0; i < stackSizeB; ++i)
{
if (stackA.elementAt(i) == null)
{
stackA.push(0);
}
}
}
if (stackA.size() > stackB.size())
{
for (int i = 0; i < stackSizeA; ++i)
{
if (stackB.elementAt(i) == null)
{
stackB.push(0);
}
}
}
}
我明白了,我已經採取了所有這些事情考慮並固定它,一切都顯示正確的數字和正確的文本:)唯一的問題,我現在是不是真的在棧上的故障的問題我需要保持與隊列類似的順序,而不是顛倒它。 [2。 3. 3.1]我想要[1,3,3,2] – SenjuXo
您可以使用大小爲(Math.max(stackA.size(),stackB.size())+ 1)的整數數組作爲中間存儲,然後從那裏構建堆棧(如果你必須使用堆棧,否則我只需要在任何地方使用數組)。請注意,storig sigle數字和使用對象數組在這裏的內存效率相當低。你可以在每個條目中存儲多個數字而不需要修改太多(基本上你會從基數10轉換爲基數1000000或類似) –
我已經編輯了我的問題,以確保兩個堆棧的大小與輸入0相同if他們不是,我原來的帖子裏面編輯的東西是關閉的嗎? @Stefan Haustein – SenjuXo