Skip to content

LeetCode: 13-Roman to Integer 解題紀錄

Last Updated on 2021-01-16 by Clay


題目

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
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:

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

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

解題思路

這題其實相當單純:將題目輸入的字串從尾端讀到開頭,並且比較這次的羅馬數字是否比上次的大。如果沒有比較大,則代表是『減去』該數值的情況,其他情況則一律直接將羅馬數字轉成對應的數值。

回傳全部加總後的結果即可。


C++ 程式碼

class Solution {
public:
    int romanToInt(string s) {
        // Init
        unordered_map<char, int> r2v= {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000},
        };
        int total_val = 0;
        int last_val = 0;
        int current_val = 0;
        
        while (!s.empty()) {
            current_val = r2v[s.back()];
            s.pop_back();
            
            if (current_val >= last_val) {
                total_val += current_val;
            }
            else {
                total_val -= current_val;
            }
            
            last_val = current_val;
        }
        
        return total_val;
    }
};


Python 程式碼

class Solution:
    def romanToInt(self, s: str) -> int:
        # Init
        r2i = {
            'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000,
        }
        
        total_val = 0
        last_val = 0
        current_val = 0
        
        while s:
            current_val = r2i[s[-1]]
            s = s[:-1]
            
            if current_val >= last_val:
                total_val += current_val
            else:
                total_val -= current_val
            
            last_val = current_val
            
        return total_val
            
        



References

Leave a Reply