zoukankan      html  css  js  c++  java
  • 栈实现两个大数相加

    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());
            }
        }
    }
  • 相关阅读:
    负载均衡session会话保持方法
    PHP分布式中Redis实现Session
    Nginx内置变量
    Nginx配置文件解析
    Nginx重写
    Nginx与Apache比较
    CGI概念
    Linux笔记(十四)
    Linux笔记(十三)
    hdu 4039
  • 原文地址:https://www.cnblogs.com/baorantHome/p/6942272.html
Copyright © 2011-2022 走看看