算法训练 表达式计算
时间限制:1.0s 内存限制:256.0MB
问题描述
输入一个只包含加减乖除和括号的合法表达式,求表达式的值。其中除表示整除。
输入格式
输入一行,包含一个表达式。
输出格式
输出这个表达式的值。
样例输入
1-2+3*(4-5)
样例输出
-4
数据规模和约定
表达式长度不超过100,表达式运算合法且运算过程都在int内进行。
import java.util.Scanner;
import java.util.Stack;
public class Main {
// 1+(2-0)*1+2
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
String str = cin.nextLine();
Stack<Character> chsta = new Stack<>(); //符号栈
Stack<Integer> numsta = new Stack<>(); //数字栈
chsta.push('#');
str += "=";
int len = str.length();
int i = 0;
while(i < len) {
// System.out.println(numsta.toString());
// System.out.println(chsta.toString());
char op = str.charAt(i);
if(op >= '0' && op <= '9') {
int num = 0;
while(op >= '0' && op <= '9') {
num = num * 10 + op - '0';
i++;
op = str.charAt(i);
}
char fu = chsta.peek();
if(fu == '-') {
num = -num;
chsta.pop();
chsta.push('+');
}
numsta.push(num);
continue;
}
if(op == '(') {
chsta.push(op);
i++;
continue;
}
if(op == ')') {
char ch2 = chsta.pop();
while(ch2 != '(') {
int a = numsta.pop();
int b = numsta.pop();
int sum = qiuzhi(b, a, ch2);
numsta.push(sum);
ch2 = chsta.pop();
}
i++;
continue;
}
//运算
char op2 = chsta.peek();
if(bijiao(op) >= bijiao(op2)) {
chsta.push(op);
i++;
continue;
}
if(bijiao(op) < bijiao(op2)) {
while(bijiao(op) < bijiao(op2)) {
char ch2 = chsta.pop();
int a = numsta.pop();
int b = numsta.pop();
int sum = qiuzhi(b, a, ch2);
numsta.push(sum);
op2 = chsta.peek();
}
chsta.push(op);
i++;
}
}
System.out.println(numsta.peek() );
// System.out.println(numsta.toString());
// System.out.println(chsta.toString());
}
public static int qiuzhi(int a, int b, char op) {
int sum = 0;
if(op == '-') {
sum = a - b;
}
if(op == '+') {
sum = a + b;
}
if(op == '*') {
sum = a * b;
}
if(op == '/') {
sum = a / b;
}
return sum;
}
public static int bijiao(char ch) {
switch(ch){
case '#': return -1;
case '=': return 0;
case '-': return 1;
case '+': return 1;
case '/': return 2;
case '*': return 2;
}
return -1;
}
}