题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
有点绕,但是一遍写注释一遍写代码就可以梳理清楚了。贴一个带注释的
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String a = in.nextLine();
System.out.println( solution(a));
}
}
// 获取计算结果
public static int solution (String a ) {
// 记录数据的栈
Stack<Integer> stack = new Stack<>();
char[] data = a.toCharArray();
// 记录当前数字
int num = 0 ;
// 默认符号为+;
char sigin = '+';
// 遍历每一位数字 并处理
for (int i = 0 ; i < data.length ; i++) {
char test = data[i];
// 如果是空格
if (String.valueOf(test) == " ") {
continue;
}
// 如果是数字
if ( Character.isDigit(test)) {
num = num * 10 + test - '0';
}
// 如果是括号
if (test == '(') {
// 记录括号的开始位置
int index = i + 1;
int end = index;
// 记录括号的个数
int count = 1;
while (count > 0) {
if (data[end] == ')') count--;
if (data[end] == '(') count ++;
end++;
}
num = solution(a.substring(index, --end));
i = end;
}
// 如果是符号
if (!Character.isDigit(test) || i == data.length - 1) {
if (sigin == '+') {
stack.push( num);
}
if (sigin == '-') {
stack.push(-1 * num);
}
if (sigin == '*') {
stack.push(stack.pop() * num);
}
if (sigin == '/') {
stack.push(stack.pop() / num);
}
sigin = test;
num = 0;
}
}
int res = 0 ;
while(!stack.empty()){
res += stack.pop();
}
return res;
}
}
#22届技术秋招#