四则运算
题目描述
输入一个表达式(用字符串表示),求这个表达式的值。保证字符串中的有效字符包括'0'-'9','+','-', '*', '', '(', ')','[', ']','{','}'。且表达式一定合法。
数据范围:表达式计算结果和过程中满足 ∣val∣≤1000 ,字符串长度满足 1≤n≤1000
输入描述
输入一个算术表达式输出描述
得到计算结果示例
输入
3+2*{1+2*[-4/(8-6)+7]}输出
25Java 编程
package cn.net.javapub.demo2.demo;
/**
* @author: shiyuwang
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while ((str = br.readLine()) != null) {
System.out.println(getResult(str));
}
}
static int pos;
public static int getResult(String str) {
Stack<Integer> val = new Stack<>();
int num = 0;
char opt = '+';
while (pos < str.length()) {
if (str.charAt(pos) == '{' || str.charAt(pos) == '(' || str.charAt(pos) == '[') {
pos++;
num = getResult(str);
}
while (pos < str.length() && Character.isDigit(str.charAt(pos))) {
num = num * 10 + str.charAt(pos) - '0';
pos++;
}
switch (opt) {
case '+':
val.push(num);
break;
case '-':
val.push(-num);
break;
case '*':
val.push(val.pop() * num);
break;
case '/':
val.push(val.pop() / num);
break;
}
num = 0;
if (pos < str.length()) {
if (str.charAt(pos) == '}' || str.charAt(pos) == ')' || str.charAt(pos) == ']') {
pos++;
break;
}
opt = str.charAt(pos);
}
pos++;
}
int sum = 0;
while (!val.isEmpty()) {
sum += val.pop();
}
return sum;
}
}展示效果:

















