Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 13. Roman to Integer

Rain Hu

13. Roman to Integer


一、題目

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:

Example 1:

Example 2:

Example 3:

Constraints:

二、分析

三、解題

1. Math

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


Share this post on:

Previous
[Leetcode] 14. Longest Common Prefix
Next
[Leetcode] 835. Image Overlap