-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword-machine.rb
More file actions
46 lines (37 loc) · 824 Bytes
/
Copy pathword-machine.rb
File metadata and controls
46 lines (37 loc) · 824 Bytes
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
def word_machine(str)
puts str
ops = str.split(' ')
stack = []
ops.each do |op|
case op
when 'POP'
return '-1' if stack.empty?
stack.pop
when 'DUP'
return '-1' if stack.empty?
stack.push(stack.last)
when '+'
return '-1' if stack.length < 2
x = stack.pop
y = stack.pop
res = x + y
return '-1' unless number_valid?(res)
stack.push(res)
when '-'
return '-1' if stack.length < 2
x = stack.pop
y = stack.pop
res = x - y
return '-1' unless number_valid?(res)
stack.push(res)
else
res = op.to_i
return '-1' unless number_valid?(res)
stack.push(res)
end
end
stack.empty? ? '-1' : stack.last.to_s
end
def number_valid?(number)
number >= 0 && number <= (2**20) - 1
end