計蒜客-加減乘除
阿新 • • 發佈:2019-01-09
給出一個表示式,其中運算子僅包含 +
,-
,*
,/
,^
要求求出表示式的最終值在這裡,/
為整除最終結果為正整數,資料保證不需要使用高精度!
輸入僅一行,即為表示式。
輸出僅一行,既為表示式算出的結果 結果小於 long
int
的最大範圍,且整個計算的過程中,也不會超過long
int
的最大範圍。
表示式總長度 ≤20
樣例輸入
2^3+1
樣例輸出
9
/* 思路:將表示式*^/先計算,留下+-式子在一次性解決 (ps:程式碼寫得冗餘了...) */ import java.util.LinkedList; import java.util.Scanner; public class Main { public static int cnt = 0; public static void main(String[] args) { Scanner cin = new Scanner(System.in); String str = cin.next(); //1.建立連結串列模擬棧,而在最終解決+-式子用連結串列 LinkedList<Integer> list = new LinkedList<>(); LinkedList<Character> oper = new LinkedList<>(); while(true) { //2.取出數值並壓入棧中,若表示式結束便退出 int num = Number(str); list.push(num); if(cnt >= str.length())break; /* 3.由於^的優先順序較高,所以要是遇到^, 便直接取出數值進行計算在壓入棧中,表示式結束便退出 */ if(str.charAt(cnt)=='^') { ++cnt; list.push((int)Math.pow(list.pop(), Number(str))); if(cnt >= str.length())break; } /* 4.若操作符棧不為空,並且頂部元素為/*, 那麼取出數值進行計算在壓入棧中, 再將操作符也壓入操作符棧中 */ if(!oper.isEmpty()&&IsOperator(oper.peek())) { int b = list.pop(); int a = list.pop(); list.push(Calc(a,b,oper.pop())); } oper.push(str.charAt(cnt++)); } /* 5.由於尾部可能還會在出現一次/或*,所以判斷將其解決 再解決+-式子便可 */ if(!oper.isEmpty()&&IsOperator(oper.peek())) { int b = list.pop(); int a = list.pop(); list.push(Calc(a,b,oper.pop())); } while(!oper.isEmpty()) { int a = list.pollLast(); int b = list.pollLast(); list.add(Calc(a,b,oper.pollLast())); } System.out.println(list.pop()); } //取出數值函式 public static int Number(String str) { int num = 0; while(cnt < str.length() && Character.isDigit(str.charAt(cnt))) { num *= 10; num += str.charAt(cnt++)-'0'; } return num; } public static int Calc(int a,int b,char ch) { switch(ch) { case '+':return a+b; case '-':return a-b; case '*':return a*b; case '/':return a/b; default:return 0; } } public static boolean IsOperator(char ch) { return ch=='*'||ch=='/'; } }