rambless
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) {
String str = in.nextLine();
str = str.replace("{", "(");
str = str.replace("[", "(");
str = str.replace("}", ")");
str = str.replace("]", ")");
System.out.println(cal(str));
}
}
//num记录上个运算结果,sign为上个运算符,遇到符号位时运算之前的数据,故最后一位索引时要走符号逻辑
public static int cal(String s) {
Deque<Integer> stack = new LinkedList<>();
char[] arr = s.toCharArray();
int num = 0;
char sign = '+';
for(int i=0; i<arr.length; i++) {
if(arr[i] == ' ') {
continue;
}
if(Character.isDigit(arr[i])) {
//如果是数字
num = num*10 + arr[i] - '0';
}
if(arr[i] == '(') {
//如果是括号,判断括号起始位置,递归
int j = i+1;
int count = 1;
while(count>0) {
if(arr[j] == ')') {
count--;
}
if(arr[j] == '(') {
count++;
}
j++;
}
num = cal(s.substring(i+1, j-1));
//循环结束后i会自增,i索引需前移一位到右括号位置
i = j-1;
}
if(!Character.isDigit(arr[i]) || i == s.length()-1){
//如果是运算符或者最后一位
if(sign == '+') {
stack.push(num);
} else if(sign == '-') {
stack.push(-1*num);
} else if(sign == '*') {
stack.push(stack.pop()*num);
} else if(sign == '/') {
stack.push(stack.pop()/num);
}
//符号提前转换,参与下一次运算
sign = arr[i];
num = 0;
}
}
int sum = 0;
while(!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}

查看5道真题和解析