题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/5759c29a28cb4361bc3605979d5a6130
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
class Solution {
public static final HashMap<String, Integer> map = new HashMap<>();
static {
map.put("+", 1);
map.put("-", 1);
map.put("*", 2);
map.put("/", 2);
}
static double exec(double n1, double n2, String op) {
switch (op) {
case "+":
return n1 + n2;
case "-":
return n1 - n2;
case "*":
return n1 * n2;
case "/":
return n1 / n2;
default:
return 0;
}
}
static double getAns(String exel) {
String[] exSplit = exel.split(" ");
Stack<String> opStack = new Stack<>();
Stack<Double> numStack = new Stack<>();
for (int i = 0; i < exSplit.length; i++) {
String s = exSplit[i];
if (map.containsKey(s)) {
while (!opStack.isEmpty() && map.get(opStack.peek()) >= map.get(s)) {
String op = opStack.pop();
double n2 = numStack.pop();
double n1 = numStack.pop();
numStack.push(exec(n1, n2, op));
}
opStack.push(s);
} else {
numStack.push(Double.parseDouble(s));
}
}
while (!opStack.isEmpty()) {
String op = opStack.pop();
double n2 = numStack.pop();
double n1 = numStack.pop();
numStack.push(exec(n1, n2, op));
}
return numStack.peek();
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String exel = scanner.nextLine();
if ("0".equals(exel))
break;
System.out.printf("%.2f\n", Solution.getAns(exel));
}
}
}
