题解 | #四则运算#
四则运算
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 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String exp = in.next();
//括号替换
String s = exp.replaceAll("\\[", "(");
String s1 = s.replaceAll("\\{", "(");
String s2 = s1.replaceAll("\\}", ")");
String s3 = s2.replaceAll("\\]", ")");
//System.out.println(s3);
int length = s3.length();
//操作数和运算符
Stack<Character> op = new Stack<>();
Stack<Integer> data = new Stack<>();
for (int i = 0; i < length; i++) {
char ch = s3.charAt(i);
//操作数
if (Character.isDigit(ch)) {
//提取数字
int index = i;
while (index != length-1 && Character.isDigit(s3.charAt(index))) {
index++;
}
String temp = "";
if (i != length - 1) {
temp = s3.substring(i, index);
} else {
temp = s3.substring(index, length);
}
int num = Integer.parseInt(temp);
data.push(num);
//下标跳转
if (i != length - 1) {
i = index - 1;
}
continue;
}
//运算符
if (op.isEmpty() || ch == '(') {
//如果是正负号,在前面加一个0
if (ch == '+' || ch == '-') {
if (i - 1 < 0 || s3.charAt(i - 1) == '(') {
data.push(0);
}
}
//符号入栈
op.push(ch);
} else if (ch == ')') {
//进行计算
while (op.peek() != '(') {
compute(op, data);
}
//左括号出栈
char wasted = op.pop();
} else if (ch == '+' || ch == '-') {
//检查优先级:真不为空且栈顶元素不为左括号,一直进行出栈运算
while (!op.isEmpty() && op.peek() != '(') {
compute(op, data);
}
//正负号前加0
if (i - 1 < 0 || s3.charAt(i - 1) == '(') {
data.push(0);
}
op.push(ch);
} else if (ch == '*' || ch == '/') {
//优先级检查
while (!op.isEmpty() &&op.peek() != '('&& op.peek() != '+' && op.peek() != '-') {
compute(op, data);
}
op.push(ch);
}
}
//继续计算
while (!op.isEmpty()) {
compute(op, data);
}
System.out.print(data.pop());
}
}
public static void compute(Stack<Character> op, Stack<Integer> data) {
char operator=op.pop();
int right=data.pop();
int left=data.pop();
//结果
int res=-1;
if(operator=='+'){
res=left+right;
}else if(operator=='-'){
res=left-right;
}else if(operator=='*'){
res=left*right;
}else{
res=res=left/right;
}
data.push(res);
}
}
美的集团公司福利 819人发布