题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int res = calculate(str); System.out.println(res); } public static int calculate(String s) { s = s.replaceAll("\\{", "("); s = s.replaceAll("\\}", ")"); s = s.replaceAll("\\[", "("); s = s.replaceAll("\\]", ")"); s = s.replaceAll("--", "+"); s = s.replaceAll("\\+-", "-"); s = s.replaceAll("-\\+", "-"); s = s.replaceAll("\\+\\+", "+"); int start = -1, end = -1; if (s.contains("+") || s.contains("-") || s.contains("*") || s.contains("/") || s.contains("(") || s.contains(")")) { //计算小括号,先找出第一个左括号(的位置,再找出其对应的右括号) //然后截取括号中间部分的字符串进行递归运算,将所得结果再插入原式替代原来的括号 start = s.indexOf("("); int temp = 0; for (int i = start + 1; i < s.length(); i++) { if (s.charAt(i) == '(') { temp++; } if (s.charAt(i) == ')') { if (temp == 0) { end = i; break; } else { temp--; } } } if (start != -1 && end != -1) { int res = calculate(s.substring(start + 1, end)); return calculate(s.substring(0,start) + String.valueOf(res) + s.substring(end + 1)); } //计算乘法,确定乘号*左右两边的乘数在字符串中的位置,再切割出乘数a、b int x = s.indexOf("*"); if (x != -1) { int m = x - 1, n = x + 1; if (s.charAt(x + 1) == '-' || s.charAt(x + 1) == '+') n = x + 2; while (m >= 0 && Character.isDigit(s.charAt(m))) { m--; } while (n < s.length() && Character.isDigit(s.charAt(n))) { n++; } int a = Integer.parseInt(s.substring(m + 1, x)); int b = Integer.parseInt(s.substring(x + 1, n)); int res = a * b; return calculate(s.substring(0, m + 1) + String.valueOf(res) + s.substring(n)); } //计算除法,确定除号/左右两边的除数与被除数在字符串中的位置,再切割出除数与被除数a、b int y = s.indexOf("/"); if (y != -1) { int m = y - 1, n = y + 1; if (s.charAt(y + 1) == '-' || s.charAt(y + 1) == '+') n = y + 2; while (m >= 0 && Character.isDigit(s.charAt(m))) { m--; } while (n < s.length() && Character.isDigit(s.charAt(n))) { n++; } int a = Integer.parseInt(s.substring(m + 1, y)); int b = Integer.parseInt(s.substring(y + 1, n)); int res = a / b; return calculate(s.substring(0, m + 1) + String.valueOf(res) + s.substring(n)); } //计算加减法,分别用正负号和数字分割字符串,得出数字数组与符号数组,以便进行计算 //应分为两种情况:2+3(数字在前)、-2-3(正负号在前) int sum; String[] digitArr = s.split("[+-]"); String[] charArr = s.split("[0-9]+"); if (s.charAt(0) == '+' || s.charAt(0) == '-') { sum = 0; for (int i = 0; i < charArr.length; i++) { if ("-".equals(charArr[i])) { sum = sum - Integer.parseInt(digitArr[i + 1]); } else if ("+".equals(charArr[i])) { sum = sum + Integer.parseInt(digitArr[i + 1]); } } } else { sum = Integer.parseInt(digitArr[0]); for (int i = 1; i < charArr.length; i++) { if ("-".equals(charArr[i])) { sum = sum - Integer.parseInt(digitArr[i]); } else if ("+".equals(charArr[i])) { sum = sum + Integer.parseInt(digitArr[i]); } } } return sum; } //若没有符号,只有数字,则直接转为数字返回 return Integer.parseInt(s); } }