-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
42 lines (27 loc) · 703 Bytes
/
Solution.rb
File metadata and controls
42 lines (27 loc) · 703 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
# @param {String} s
# @return {Integer}
def roman_to_int(s)
#Contruct a conversion map.
valueMap = {'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000}
result = 0
accumulator = 0
currentMaxUnit = 0
s.each_char do |ch|
if result < valueMap[ch]
result = valueMap[ch] - result
currentMaxUnit = valueMap[ch]
else
if valueMap[ch] < currentMaxUnit
accumulator += result
result = 0
currentMaxUnit = valueMap[ch]
end
result += valueMap[ch]
end
end
accumulator += result
end
puts roman_to_int 'I'
puts roman_to_int 'V'
puts roman_to_int 'IVM'
puts roman_to_int "MCMXCVI" # 1996