Skip to content

Instantly share code, notes, and snippets.

@junbaor
Created May 11, 2018 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junbaor/2b23f25d856cb2997da1657483833bac to your computer and use it in GitHub Desktop.
Save junbaor/2b23f25d856cb2997da1657483833bac to your computer and use it in GitHub Desktop.
java 计算数学公式
package com.junbaor.demo;
import java.util.Stack;
public class EvaluateMain {
public static void main(String[] args) {
//从左到右计算, 支持小括号
System.out.println(calcEvaluate("(1+2+4)*3-(8+2)"));
}
public static int calcEvaluate(String evaluate) {
evaluate = evaluate.replace(" ", "").trim();
Stack<Integer> numericalStack = new Stack<>();
Stack<Character> operationStack = new Stack<>();
char[] chars = evaluate.toCharArray();
for (char item : chars) {
if (item == '+' || item == '-' || item == '*' || item == '/') {
if (!operationStack.isEmpty() && operationStack.peek() != '(') {
calc(numericalStack, operationStack);
}
operationStack.push(item);
} else if (item == '(') {
operationStack.push(item);
} else if (item == ')') {
calc(numericalStack, operationStack);
operationStack.pop();// 把左括号丢弃
} else {
numericalStack.push(Integer.valueOf(String.valueOf(item)));
}
}
calc(numericalStack, operationStack);
return numericalStack.pop();
}
public static void calc(Stack<Integer> numericalStack, Stack<Character> operationStack) {
Integer pop2 = numericalStack.pop();
Integer pop1 = numericalStack.pop();
Character operation = operationStack.pop();
if (operation == '+') {
numericalStack.push(pop1 + pop2);
} else if (operation == '-') {
numericalStack.push(pop1 - pop2);
} else if (operation == '*') {
numericalStack.push(pop1 * pop2);
} else if (operation == '/') {
numericalStack.push(pop1 / pop2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment