- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0013-roman-to-integer.rb
44 lines (38 loc) · 794 Bytes
/
0013-roman-to-integer.rb
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
# frozen_string_literal: true
# 13. Roman to Integer
# https://leetcode.com/problems/roman-to-integer
ROMAN_VALUES={
"I"=>1,
"V"=>5,
"X"=>10,
"L"=>50,
"C"=>100,
"D"=>500,
"M"=>1000
}.freeze
# @param {String} s
# @return {Integer}
defroman_to_int(s)
sum=0
v=0
s.chars.each_with_indexdo |c,i|
ifs[i + 1] && ROMAN_VALUES[c] < ROMAN_VALUES[s[i + 1]]
v=ROMAN_VALUES[c]
else
sum += ROMAN_VALUES[c] - v
v=0
end
end
sum
end
# ********************#
# TEST #
# ********************#
require"test/unit"
classTest_roman_to_int < Test::Unit::TestCase
deftest_
assert_equal3,roman_to_int("III")
assert_equal58,roman_to_int("LVIII")
assert_equal1994,roman_to_int("MCMXCIV")
end
end