13. Roman to Integer

  • Hardness: \(\color{green}\textsf{Easy}\)
  • Ralated Topics: Hash TableMathString

一、題目

Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.
\(\boxed{\begin{array}{ll} \textbf{Symbol}&\textbf{Value}\\ \texttt{I}&1\\ \texttt{V}&5\\ \texttt{X}&10\\ \texttt{L}&50\\ \texttt{C}&100\\ \texttt{D}&500\\ \texttt{M}&1000\\ \end{array}}\)
For example, 2 is written as II in Roman numeral, just two one’s added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.
    Given a roman numeral, convert it to an integer.

Example 1:

  • Input: s = “III”
  • Output: 3
  • Explanation: III = 3.

Example 2:

  • Input: s = “LVIII”
  • Output: 58
  • Explanation: L = 50, V = 5, III = 3.

Example 3:

  • Input: s = “MCMXCIV”
  • Output: 1994
  • Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Constraints:

  • 1 <= s.length <= 15
  • s contains only the character ('I', 'V', 'X', 'L', 'C', 'D', 'M')
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

二、分析

  • 將字串從後往前分析,有助於解題。
  • I 可以當 1 也可以當 -1,當 -1 的情況是 I 的後面接的是 V 或是 X 時。
  • X 可以當 10 也可以當 -10,當 -10 的情況是 X 的後面接的是 V 或是 X 時。
  • C 可以當 100 也可以當 -100,當 -100 的情況是 C 的後面接的是 V 或是 X 時。

三、解題

1. Math

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)
int romanToInt(string s) {
    unordered_map<char,int> map = {
        {'I', 1},
        {'V', 5},
        {'X', 10},
        {'L', 50},
        {'C', 100},
        {'D', 500},
        {'M', 1000}
    };
    int res = 0;
    for (int i = s.length()-1; i >=0; i--) {
        if (res > 4*map[s[i]])
            res -= map[s[i]];
        else 
            res += map[s[i]];
    }
    return res;
}

回目錄 Catalog