在一个表达式中,只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,请求出表达式的值。(“/”用整数除法)。
输入格式:
共1 行,为一个算式。 (算式长度<=30 其中所有数据在 0~2^31-1的范围内)。
输出格式:
共一行,为表达式的值。
输入样例:
在这里给出一组输入。例如:
1+(3+2)(7^2+69)/(2)
输出样例:
在这里给出相应的输出。例如:
258
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.next();
char[] e = a.toCharArray();
Stack<Character> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
int x1;
int x2;
for(int i=0;i<e.length;i++)
{
if(e[i] >= '0' && e[i] <= '9')
{
int num;
num = e[i]-'0';
while(i<e.length-1)
{
if(!(e[i+1] >= '0' && e[i+1] <= '9'))
{
break;
}
num *= 10;
num += (e[i+1] - '0');
i++;
}
s2.push(num);
}
else if(s1.isEmpty())
{
s1.push(e[i]);
}
else if(e[i] == '(')
{
s1.push(e[i]);
}
else if(e[i] == ')')
{
char c3;
while(!s1.isEmpty() && (c3 = s1.pop()) != '(')
{
x2 = s2.pop();
x1 = s2.pop();
s2.push(calculate(x1,x2,c3));
}
}
else if(e[i] == '^')
{
if(s1.peek() == '^')
{
char c3;
c3 = s1.pop();
x2 = s2.pop();
x1 = s2.pop();
s2.push(calculate(x1,x2,c3));
}
s1.push(e[i]);
}
else if(e[i] == '+' || e[i] == '-')
{
if(s1.peek() != '(')
{
char c3;
while(!s1.isEmpty() && s1.peek() != '(')
{
c3 = s1.pop();
x2 = s2.pop();
x1 = s2.pop();
s2.push(calculate(x1,x2,c3));
}
}
s1.push(e[i]);
}
else
{
char c3;
while(!(s1.peek() == '+' || s1.peek() == '-') && !s1.isEmpty() && s1.peek() != '(')
{
c3 = s1.pop();
x2 = s2.pop();
x1 = s2.pop();
s2.push(calculate(x1,x2,c3));
}
s1.push(e[i]);
}
}
while(!s1.isEmpty())
{
char c3;
c3 = s1.pop();
x2 = s2.pop();
x1 = s2.pop();
s2.push(calculate(x1,x2,c3));
}
System.out.println(s2.pop());
in.close();
}
public static int calculate(int x1,int x2,char c)
{
int sum = 0;
switch (c)
{
case '+':sum = x1+x2;break;
case '-':sum = x1-x2;break;
case '*':sum = x1*x2;break;
case '/':sum = x1/x2;break;
case '^':sum = (int) Math.pow(x1,x2);break;
}
return sum;
}
}