-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackMachineSolution.java
More file actions
56 lines (49 loc) · 1.45 KB
/
Copy pathStackMachineSolution.java
File metadata and controls
56 lines (49 loc) · 1.45 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
public static int solution(String S) {
int result = -1, value1=0, value2=0;
Stack<Integer> opStack = new Stack<Integer>();
String[] inputs = S.trim().split("\\s"); // trim spaces
for(int i = 0; i<inputs.length; i++){
try{
switch(inputs[i]){
case "+":
{
value1 = opStack.pop();
value2 = opStack.pop();
opStack.push(value1+value2);
break;
}
case "-":
{
value1 = opStack.pop();
value2 = opStack.pop();
if(value1>value2){
opStack.push(value1-value2);
break;
}
else{
System.out.println("Error in the machine: Negative Value");
return result;
}
}
case "DUP":
{
value1 = opStack.peek();
opStack.push(value1);
break;
}
case "POP":
{
opStack.pop();
break;
}
default:
opStack.push(Integer.parseInt(inputs[i]));
}
}catch(EmptyStackException e){
System.out.println("Error in the machine: Empty Stack Exception");
return result;
}
}
result = opStack.peek();
return result;
}