请写一个整数计算器,支持加减乘三种运算和括号。示例1
输入 "1+2" 返回值 3
输入 "(2*(3-4))*5" 返回值 -10
本题主要考察对于数据结构栈的使用。我们可以定义两个栈,操作数栈和操作符号栈,依次扫描输入,处理结果。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
public int solve (String s) {
// write code here
Stack<Integer> numStack = new Stack<>();
Stack<Character> opStack = new Stack<>();
opStack.push('#');
s += '#';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 处理数字
if(c >='0' && c <= '9') {
// 第一个数字直接入栈
if (i == 0) {
int num = c - '0';
numStack.push(num);
continue;
} else {
char pre = s.charAt(i-1);
// 对数字进行进位处理
if (pre >= '0' && pre <= '9') {
int num = numStack.pop() * 10 + (c - '0');
numStack.push(num);
} else {
int num = c - '0';
numStack.push(num);
}
continue;
}
} else {
// 处理加减符号运算符号
if (c == '-' || c == '+' || c == '#') {
// 处理负数
if (c == '-' && (i == 0 || s.charAt(i - 1) == '(')) {
numStack.push(0);
opStack.push('-');
continue;
}
// 处理单独加符号
if (c == '+' && (i == 0 || s.charAt(i - 1) == '(')) {
continue;
}
// 对运算符进行运算
while (opStack.peek() == '*' || opStack.peek() == '+' || opStack.peek() == '-'){
int b = numStack.pop();
int a = numStack.pop();
char op = opStack.pop();
switch (op){
case '*':
numStack.push(b * a);
break;
case '+':
numStack.push(a + b);
break;
case '-':
numStack.push(a - b);
break;
}
}
opStack.push(c);
}
if (c == '(') {
opStack.push(c);
}
// 当前是右括号,对结果进行计算
if (c == ')') {
while (opStack.peek() != '('){
int b = numStack.pop();
int a = numStack.pop();
char op = opStack.pop();
switch (op){
case '*':
numStack.push(b * a);
break;
case '+':
numStack.push(a + b);
break;
case '-':
numStack.push(a - b);
break;
}
}
// 吐出左括号
opStack.pop();
}
if (c == '*') {
opStack.push(c);
}
}
}
return numStack.peek();
}
}