rambless
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String s = in.nextLine();
s = s.replace("[", "(");
s = s.replace("{", "(");
s = s.replace("]", ")");
s = s.replace("}", ")");
System.out.println(fn(s));
}
private static int fn(String s) {
// 逻辑:碰到符号的时候放数字、碰到括号的时候算括号里边的
LinkedList<Integer> stack = new LinkedList<>();
char[] arr = s.toCharArray();
int num = 0;
char sign = '+';
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if (Character.isDigit(c)) {
num = num * 10 + Integer.parseInt(c + "");
} else if (c == '(') {
// 括号计数
int size = 1;
int j = i + 1;
while (size > 0) {
char t = s.charAt(j);
if (t == '(') {
size++;
} else if (t == ')') {
size--;
}
j++;
}
num = fn(s.substring(i + 1, j - 1));
i = j - 1;
} else {
if (sign == '+') {
stack.push(num);
} else if (sign == '-') {
stack.push(-num);
} else if (sign == '*') {
stack.push(stack.pop() * num);
} else {
stack.push(stack.pop() / num);
}
sign = c;
num = 0;
}
}
//处理最后一个数字
if (sign == '+') {
stack.push(num);
} else if (sign == '-') {
stack.push(-num);
} else if (sign == '*') {
stack.push(stack.pop() * num);
} else {
stack.push(stack.pop() / num);
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}


