题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
public class Main { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
str = str.replace('{', '(');
str = str.replace('[', '(');
str = str.replace('}', ')');
str = str.replace(']', ')');
System.out.println(solve(str));
}
static int calc(char op, int right, int left) {
switch (op) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
default:
return 0;
}
}
static int solve(String str) {
Stack<Integer> sOutNum = new Stack<Integer>();
Stack<Character> sOutOp = new Stack<Character>();
sOutNum.push(0);
sOutOp.push('+');
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isDigit(c)) {
// 前面是数字
if (i > 0 && Character.isDigit(str.charAt(i - 1))) {
sOutNum.push(sOutNum.pop() * 10 + (c - '0'));
} else if (i > 0 && str.charAt(i - 1) == '-') {
sOutOp.pop();
sOutNum.push(-1 * (c - '0'));
if(i!=1)
{
sOutOp.push('+');
}
} else {
sOutNum.push(c - '0');
}
} else {
if( (c == '+' || c == '-') && (i!=0)){
if (sOutOp.isEmpty() == false) {
int temp = calc(sOutOp.pop(), sOutNum.pop(), sOutNum.pop());
sOutNum.push(temp);
sOutOp.push(c);
} else {
sOutOp.push(c);
}
} else if (c == '*' || c == '/') {
char prev = sOutOp.peek();
if (prev == '*' || prev == '/') {
int temp = calc(sOutOp.pop(), sOutNum.pop(), sOutNum.pop());
sOutNum.push(temp);
sOutOp.push(c);
} else {
sOutOp.push(c);
}
} else if (c == '(') {
int leftBrac = 1;
int j = i + 1;
while (leftBrac > 0) {
if (str.charAt(j) == ')') {
leftBrac--;
} else if (str.charAt(j) == '(') {
leftBrac++;
}
j++;
}
int num = solve(str.substring(i + 1, j - 1));
if(i==1 && str.charAt(i-1)=='-')
{
num = num*(-1);
sOutNum.push(num);
}
if(i>1 && str.charAt(i-1)=='-')
{
sOutOp.pop();
num = num*(-1);
sOutNum.push(num);
sOutOp.push('+');
}else
{
sOutNum.push(num);
}
i = j - 1;
continue;
}else
{
sOutOp.push(c);
}
}
}
while (sOutOp.isEmpty() == false) {
int res2 = calc(sOutOp.pop(), sOutNum.pop(), sOutNum.pop());
sOutNum.push(res2);
}
return sOutNum.pop();
}
}


查看17道真题和解析