AddBigDigital

来源:互联网 发布:linux重启后dracut 编辑:程序博客网 时间:2024/05/19 17:59
package com.szl.gettime;


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


public class AddBigDigital {


    public static void main(String[] args) {
        String strNum1;
        String strNum2;
        Stack<Integer> num1 = new Stack<Integer>();
        Stack<Integer> num2 = new Stack<Integer>();
        Stack<Integer> sum = new Stack<Integer>();


        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入第一个加数:");
        strNum1 = scanner.nextLine();
        System.out.println("请输入第二个加数:");
        strNum2 = scanner.nextLine();


        int len1 = strNum1.length();
        int len2 = strNum2.length();
        for (int i = 0; i < len1; i++) {
            //按输入顺序(高位到低位)入栈1,此时栈顶为最低位
            num1.push(strNum1.charAt(i) - '0');
        }
        for (int i = 0; i < len2; i++) {
            //按输入顺序(高位到低位)入栈2,此时栈顶为最低位
            num2.push(strNum2.charAt(i) - '0');
        }


        int tmp = 0;
        while (!num1.empty() && !num2.empty()) {
            tmp += num1.pop() + num2.pop(); // 将栈1、栈2均pop出栈顶做加法,并考虑进位,结果入栈3,这时栈3正好是低位入栈
            sum.push(tmp % 10);
            tmp = tmp / 10;
        }
        while (!num1.empty()) //处理多余的栈1
        {
            tmp += num1.pop();
            num1.pop();
            sum.push(tmp % 10);
            tmp = tmp / 10;
        }
        while (!num2.empty()) //处理多余的栈2
        {
            tmp += num2.pop();
            sum.push(tmp % 10);
            tmp = tmp / 10;
        }
        if (0 != tmp) //处理多余的进位
        {
            sum.push(tmp);
        }


        System.out.println("大整数的和为:");
        while (!sum.empty()) //直接pop出栈3,即正好的从高位到低位的结果
        {
            System.out.printf("%d", sum.pop());
        }


    }
}
0 0
原创粉丝点击