13. Roman to Integer
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000Input: "III"
Output: 3Last updated
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000Input: "III"
Output: 3Last updated
Input: "IV"
Output: 4Input: "IX"
Output: 9Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.# @param {String} s
# @return {Integer}
def roman_to_int(s)
total = 0
current = 0
new_arr = s.chars
new_len = new_arr.length
begin
case new_arr[current]
when "I"
if new_arr[current+1] == "V"
total += 4
current += 2
elsif new_arr[current+1] == "X"
total += 9
current += 2
else
total += 1
current += 1
end
when "V"
total += 5
current += 1
when "X"
if new_arr[current+1] == "L"
total += 40
current += 2
elsif new_arr[current+1] == "C"
total += 90
current += 2
else
total += 10
current += 1
end
when "L"
total += 50
current += 1
when "C"
if new_arr[current+1] == "D"
total += 400
current += 2
elsif new_arr[current+1] == "M"
total += 900
current += 2
else
total += 100
current += 1
end
when "D"
total += 500
current += 1
when "M"
total += 1000
current += 1
end
end while current < new_len
total
end