-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordMachine.java
64 lines (53 loc) · 1.81 KB
/
WordMachine.java
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
import java.util.*;
public class WordMachine {
public static int solution(String S) {
// write your code in Java SE 8
Stack<Integer> st = new Stack<Integer>();
String[] split = S.split("\\s+");
int result = -1;
try {
for (int i = 0; i < split.length; i++) {
if (isInteger(split[i], 10)) {
st.push(Integer.parseInt(split[i]));
} else {
int value1 = -1;
int value2 = -1;
switch (split[i]) {
case "POP":
st.pop();
break;
case "DUP":
value1 = (int) st.peek();
st.push(value1);
break;
case "+":
value1 = Integer.valueOf(st.pop());
value2 = Integer.valueOf(st.pop());
st.push(value1 + value2);
break;
case "-":
value1 = Integer.valueOf(st.pop());
value2 = Integer.valueOf(st.pop());
st.push(value1 - value2);
break;
}
}
}
result = Integer.valueOf(st.peek());
} catch (Exception e) {
return result;
}
return result;
}
public static boolean isInteger(String s, int radix) {
Scanner sc = new Scanner(s.trim());
if (!sc.hasNextInt(radix))
return false;
sc.nextInt(radix);
return !sc.hasNext();
}
public static void main(String[] args) {
String s = "13 DUP 4 POP 5 DUP + DUP + -";
System.out.println(solution(s));
}
}