题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line = in.nextLine();
System.out.println(cal(line));
}
/** 根据表达式计算 */
public static int cal(String expression) {
char[] chars = expression.toCharArray();
//算式可抽象为 已计算值 + 未计算值 上一个符号(+-x/) 当前值
//每次取完一个数值后判断
//如上一符号为+-号,已计算值=已计算值+未计算值,未计算值=+-当前值
//如上一符号为*/号,未计算值=未计算值*/当前值
int p = 0; //计算指针
int hasCal = 0; //已计算的部分
int noCal = 0; //未计算的部分
char symbol = '+'; //上一个符号
while (true) {
//每一轮取一个数字和一个符号
int number = 0;
//数字时,取出一个数字
while (p < chars.length && Character.isDigit(chars[p])) {
number = number * 10 + (chars[p] - '0');
p++;
}
//括号时,子结构递归,最终还是取出一个数字
if (p < chars.length && (chars[p] == '(' || chars[p] == '[' ||
chars[p] == '{')) {
int left = p;
int leftCount = 1, rightCount = 0;
while (leftCount != rightCount) {
p++;
if (chars[p] == '(' || chars[p] == '[' || chars[p] == '{') {
leftCount++;
} else if (chars[p] == ')' || chars[p] == ']' || chars[p] == '}') {
rightCount++;
}
}
number = cal(expression.substring(left + 1, p));
p++;
}
//取完了数字,根据上一个符号,判断如何计算,+-号计算已计算部分跟未计算部分,并把当前值置为未计算部分;*/号则将当前值计算到未计算部分
switch (symbol) {
case '+':
hasCal = hasCal + noCal;
noCal = number;
break;
case '-':
hasCal = hasCal + noCal;
noCal = -number;
break;
case '*':
noCal = noCal * number;
break;
case '/':
noCal = noCal / number;
break;
}
//如表达式结束,结束循环
if (p >= chars.length) {
break;
}
//数字取完了,只会是符号
symbol = chars[p];
p++;
}
return hasCal + noCal;
}
}

查看3道真题和解析