IDG | 四則運算運算式計算

來源:互聯網
上載者:User

標籤:idg   逆波蘭   四則運算   

分析

首先將中綴運算式轉換為尾碼運算式(逆波蘭式),然後使用棧進行計算。

沒有考慮括弧、小數。

代碼

import java.util.LinkedList;import java.util.List;import java.util.Stack;public class ExpCal {public static double calc(String exp) {if (exp == null || exp.length() <= 0) {throw new IllegalArgumentException();}char[] c = exp.toCharArray();Stack<Character> s = new Stack<Character>();List<String> reversePolishNotation = new LinkedList<String>();for (int i = 0; i < c.length; ++i) {if (c[i] == '+' || c[i] == '-' || c[i] == '*' || c[i] == '/') {while (!s.isEmpty() && compOp(s.peek(), c[i]) >= 0) {reversePolishNotation.add(String.valueOf(s.pop()));}s.push(c[i]);} else {StringBuilder sb = new StringBuilder();while (i < c.length && c[i] >= '0' && c[i] <= '9') {sb.append(c[i++]);}reversePolishNotation.add(sb.toString());--i;}}while (!s.isEmpty()) {reversePolishNotation.add(String.valueOf(s.pop()));}Stack<Double> num = new Stack<Double>();for (String e : reversePolishNotation) {if (e.equals("+")) {num.push(num.pop() + num.pop());} else if (e.equals("-")) {double a = num.pop();double b = num.pop();num.push(b - a);} else if (e.equals("*")) {num.push(num.pop() * num.pop());} else if (e.equals("/")) {double a = num.pop();double b = num.pop();num.push(b / a);} else {num.push(Double.parseDouble(e));}}return num.pop();}private static int compOp(char a, char b) {return getPri(a) - getPri(b);}private static int getPri(char c) {switch (c) {case '+':case '-':return 1;case '*':case '/':return 2;default:return 0;}}public static void main(String[] args) {System.out.println(calc("4*3+2*5-8/8-2*6/3+2/1-4"));}}

IDG | 四則運算運算式計算

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.