Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
# @param {String} s
# @return {Integer}
def roman_to_int(s)
arr = s.split("")
last_idx = arr.size - 1
sum = 0
arr.each_with_index do |str, idx|
case str
when "I"
if idx != last_idx && (arr[idx + 1] == "V" || arr[idx + 1] == "X")
sum -= 1
else
sum += 1
end
when "V"
sum += 5
when "X"
if idx != last_idx && (arr[idx + 1] == "L" || arr[idx + 1] == "C")
sum -= 10
else
sum += 10
end
when "L"
sum += 50
when "C"
if idx != last_idx && (arr[idx + 1] == "D" || arr[idx + 1] == "M")
sum -= 100
else
sum += 100
end
when "D"
sum += 500
when "M"
sum += 1000
end
end
sum
end
馬鹿正直に実装してみた😛