问题描述

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

罗马数字

**I, II, III, IV, V, VI, VII, VIII, IX, X**
 Symbol ​I​ ​V​ ​X​ ​L​ ​C​ ​D​ ​M​ Value 1 5 10 50 100 500 1,000

Python

代码

class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = dict(I=1,V=5,X=10,L=50,C=100,D=500,M=1000)
res = 0
for i in range(len(s)-1):
if roman[s[i]] < roman[s[i+1]]:
res -= roman[s[i]]
else:
res += roman[s[i]]
return res + roman[s[len(s)-1]]

Java

public int romanToInt(String s) {
int result = 0;
HashMap<String, Integer> roman = new HashMap() {
{
put("I", 1);
put("V", 5);
put("X", 10);
put("L", 50);
put("C", 100);
put("D", 500);
put("M", 1000);
}
};
for (int i = 0; i < s.length(); i++) {
if (i == s.length() - 1) {
return result + roman.get("" + s.charAt(i));
}
if (roman.get("" + s.charAt(i)) >= roman.get("" + s.charAt(i + 1))) {
result += roman.get("" + s.charAt(i));
} else {
result -= roman.get("" + s.charAt(i));
}
}
return result;
}

Go

package main
import (
"fmt"
)
var roman_dict = map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 10000}
func romanToInt(roman string) int {
result := 0
for i := 0; i < len(roman)-1; i++ {
current, next := roman_dict[roman[i]], roman_dict[roman[i+1]]
if current < next {
result -= current
} else {
result += current
}
}
end := roman_dict[roman[len(roman)-1]]
return result + end
}
func main() {
fmt.Println(romanToInt("IXV"))
}