IDG | four arithmetic expressions

Source: Internet
Author: User

Analysis

First, convert the infix expression to the suffix expression (inverse polish expression), and then use the stack for calculation.

Parentheses and decimals are not considered.

Code

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 | four arithmetic expressions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.