分析
首先將中綴表示式轉換為字尾表示式(逆波蘭式),然後使用棧進行計算。
沒有考慮括號、小數。
程式碼
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()) {
Stack<Double> num = new Stack<Doub
分析
首先將中綴表示式轉換為字尾表示式(逆波蘭式),然後使用棧進行計算。
沒有考慮括號、小數。
程式碼
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<Doub