棧實現兩個大數相加

import java.util.Scanner;
import java.util.Stack;

public class JavaDemo {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        /**
         * 第一個大數入棧
         */
        System.out.println("輸入第一個大數:");
        String firstNum = scanner.nextLine();
        Integer integer = Integer.valueOf(firstNum);
        Stack firstStack = new Stack<Integer>();
        for (int n = 0; n < firstNum.length(); n++) {
            firstStack.push(integer % 10);// 從個位開始壓入棧
            integer = integer / 10;
        }
        /**
         * 第二個大數入棧
         */
        System.out.println("輸入第二個大數:");
        String secondNum = scanner.nextLine();
        Integer integer2 = Integer.valueOf(secondNum);
        Stack secondStack = new Stack<Integer>();
        for (int n = 0; n < secondNum.length(); n++) {
            secondStack.push(integer2 % 10);// 從個位開始壓入棧
            integer2 = integer2 / 10;
        }
        /**
         * 兩個大數開始作加法運算
         */
        int in = 0;// 每一個位置上數字運算後進位
        int middle = 0;// 每一個位置上相加所得結果
        Stack thirdStack = new Stack<Integer>();// 存取結果的棧
        while (!firstStack.isEmpty() || !secondStack.isEmpty()) {
            middle = (int) firstStack.pop() + (int) secondStack.pop() + in;
            thirdStack.push(middle % 10);
            in = middle / 10;
            middle = middle / 10;
        }
        while (!thirdStack.isEmpty()) {
            System.out.print(thirdStack.pop());
        }
    }
}
相關文章
相關標籤/搜索