首页 > 代码库 > 栈实现两个大数相加

栈实现两个大数相加

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());
        }
    }
}

 

栈实现两个大数相加