-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpression.java
More file actions
67 lines (67 loc) · 1.26 KB
/
Expression.java
File metadata and controls
67 lines (67 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
class Expression
{
int max;
int top;
int st[];
Expression(int m)
{
max=m;
top=-1;
st=new int[max];
}
void push(int s)
{
if(top==max-1){
System.out.println("Stack Overflow");
return;
}
else
st[++top]=s;
}
int pop()
{
if(top==-1)
{
System.out.println("Stack Underflow");
return 0;
}
else
return st[top--];
}
boolean isEmpty()
{
if(top==-1)
return true;
return false;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String arr[]=in.nextLine().replaceAll("[\\[\\]\"]","").split(",\\s*");
Expression obj=new Expression(arr.length);
for(String t:arr)
{
if(t.matches("-?\\d+"))
obj.push(Integer.parseInt(t));
else
{
int b=obj.pop();
int a=obj.pop();
int res=0;
switch(t){
case "+": res=a+b;
break;
case "-": res=a-b;
break;
case "*": res=a*b;
break;
case "/": res=a/b;
break;
}
obj.push(res);
}
}
System.out.println(obj.pop());
}
}