Roman to Integer

Description

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

将罗马数字转换成整型。

Solution

 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
func romanToInt(s string) int {
    num := map[uint8]int{
        'M': 1000,
        'D': 500,
        'C': 100,
        'L': 50,
        'X': 10,
        'V': 5,
        'I': 1,
    }

    length := len(s)

    if length == 0 {
        return 0
    }

    res := num[s[length-1]]
    for i := length - 2; i >= 0; i-- {
        n := num[s[i]]

        if n < num[s[i+1]] {
            res -= n
        } else {
            res += n
        }
    }

    return res
}

Similar Problem

12. Integer to Roman