题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static int i = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str=in.nextLine();
char[] ch = str.toCharArray();
System.out.println(compute(ch));
}
}
private static int compute(char[] ch) {
Stack<Integer> stack = new Stack<>();
int num = 0;
int length = ch.length;
char sign = '+';
while (i < length) {
if (ch[i] == '{' || ch[i] == '[' || ch[i] == '(') {
i++;
num = compute(ch);//递归
}
//碰到符号跳出while,多位数字循环计算
while (i < length && Character.isDigit(ch[i])) {
num = num * 10 + (ch[i] - '0'); //多位数字×膜(10)计算结果
i++;
}
//sign=运算符就对栈进行操作
if(sign=='+')stack.push(num);
else if(sign=='-')stack.push(-num);
else if(sign=='*')stack.push(stack.pop()*num);
else if(sign=='/')stack.push(stack.pop()/num);
// 不能用 else stack.push(stack.pop()/num);因为else包括sign=非运算符号的情况,直接用四个if也可
if(i>=length)break;//最后一层递归可能越界
num = 0; //更新计数器
// if (ch[i] == '-' || ch[i] == '+' || ch[i] == '*' || ch[i] == '/') {
sign = ch[i];//这里不用判断是否是运算符,营外sign=其他符号的话不对栈进行操作
//}//更新符号
if (ch[i] == '}' || ch[i] == ']' || ch[i] == ')') {
i++;
break;
//处理完一个括号跳出一层递归
}
i++;//没有碰到回括号,指针后移
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}
