13. Roman to Integer
https://leetcode.com/problems/roman-to-integer/
js
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
var vals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var symbols = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
var result = 0
for (let i = 0; s.length > 0; i++) {
while (s.startsWith(symbols[i])) {
s = s.substring(symbols[i].length)
result += vals[i]
}
}
return result
}
py
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
vals = [
1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1
]
symbols = [
'M', 'CM', 'D', 'CD', 'C', 'XC',
'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'
]
result = 0
i = 0
while len(s) > 0:
while s.startswith(symbols[i]):
s = s[len(symbols[i]):]
result += vals[i]
i += 1
return result
go
func romanToInt(s string) int {
vals := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
result := 0
for i := 0; len(s) > 0; i++ {
symLen := len(symbols[i])
for len(s) >= symLen {
if s[:symLen] == symbols[i] {
result += vals[i]
s = s[symLen:]
} else {
break
}
}
}
return result
}