题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); // 小括号优先级>中括号>大括号 str = str.replaceAll("\\[", "("); str = str.replaceAll("]", ")"); str = str.replaceAll("\\{", "("); str = str.replaceAll("}", ")"); System.out.println(getNum(str)); } private static int getNum(String str) { char[] chars = str.toCharArray(); int num = 0; char sign = '+'; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < chars.length; i++) { // 组合数字 char val = chars[i]; if (Character.isDigit(val)) { num = num * 10 + Integer.valueOf(String.valueOf(val)); } else if (val == '(') { int count = 1; int j = i + 1; while (count > 0) { if (chars[j] == ')') count--; if (chars[j] == '(') count++; j++; } // 得到括号的最终下标 num = getNum(str.substring(i + 1, j - 1)); i = j - 1; } if (!Character.isDigit(chars[i]) || i == str.length() - 1) { // 运算 if (sign == '+') { stack.push(num); } else if (sign == '-') { stack.push(num * -1); } else if (sign == '*') { stack.push(num * stack.pop()); } else if (sign == '/') { stack.push(stack.pop() / num); } sign = chars[i]; num = 0; } } int res = 0; while (!stack.isEmpty()) { res += stack.pop(); } return res; } }
这道题的点其实就是大中小括号都可以替换成小括号。
但是我个人还是喜欢用这种方式,
public static void main(String[] args) throws ScriptException { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); // 小括号优先级>中括号>大括号 str = str.replaceAll("\\[", "("); str = str.replaceAll("]", ")"); str = str.replaceAll("\\{", "("); str = str.replaceAll("}", ")"); ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn"); System.out.println(scriptEngine.eval(str)); //System.out.println(getNum(str)); }