[華為機試] 簡單運算式計算


題目:表達式計算,只含有正整數,加號,減號,乘號,表達式語法正確,即兩個數字間只有一個運算符,不用考慮極大數及溢出的情況。

代碼:

 

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

public class SimpleCalculator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        Stack<Integer> splitNums = getSplitNums(line);
        Stack<String> splitStrs = getSplitStrs(line); 
        int res = getCalculationResult(splitNums, splitStrs);
        scanner.close();
        System.out.println(res);
    }

    public static Stack<Integer> getSplitNums(String line) {
        Stack<Integer> stackS = new Stack<>();
        String[] strArray = line.split("\\+|-|\\*");
        for(String s:strArray) {
            stackS.push(Integer.parseInt(s));
        }
        return stackS;
    }

    public static Stack<String> getSplitStrs(String line){
        Stack<String> stackS = new Stack<>();
        String[] strArray = line.split("[0-9]+");
        for(String s:strArray) {
            if(!s.equals("")){
                stackS.push(s);
            }
        }
        return stackS;
    }

    public static int getCalculationResult(Stack<Integer> nums, Stack<String> symbles) {
        Stack<Integer> numsStack = new Stack<>();
        Stack<String> symStack = new Stack<>();
        numsStack.push(nums.pop());
        while(!symbles.isEmpty()) {
            String symble = symbles.pop();
            if(symble.equals("*")) {
                numsStack.push(nums.pop() * numsStack.pop());
            }else {
                symStack.push(symble);
                numsStack.push(nums.pop());
            }
        }

        while(!symStack.isEmpty()) {
            int num = numsStack.pop();
            String symble = symStack.pop();
            if(symble.equals("+")){
                numsStack.push(num + numsStack.pop());
            }else if(symble.equals("-")) {
                numsStack.push(num - numsStack.pop());
            }
        }
        return numsStack.pop();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM