KatInterview

13. Roman to Integer

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to convert a Roman numeral string into its corresponding integer value. Roman numerals are composed of seven symbols: I, V, X, L, C, D, and M. Typically, numerals are written from largest to smallest, and their values are added together. For example, XII is 10 + 1 + 1 = 12. The main challenge lies in the six instances where subtraction is used: a smaller value symbol placed before a larger value symbol indicates subtraction. For example, IV is 5 - 1 = 4, and CM is 1000 - 100 = 900.

Solution

Roman to Integer in Python

class Solution:
    def romanToInt(self, s: str) -> int:
        # Map to store Roman numerals and their integer values.
        m = {
            'I': 1,
            'V': 5,
            'X': 10,
            'L': 50,
            'C': 100,
            'D': 500,
            'M': 1000
        }
        
        # Initialize total with the value of the last character.
        total = m[s[-1]]
        
        # Iterate from the second-to-last character to the beginning.
        for i in range(len(s) - 2, -1, -1):
            # If the value of the current character is less than the value of the character to its right,
            # it's a subtractive case (like IV, IX).
            if m[s[i]] < m[s[i+1]]:
                total -= m[s[i]]
            else:
                # Otherwise, it's an additive case.
                total += m[s[i]]
                
        return total

Roman to Integer in Java

class Solution {
    public int romanToInt(String s) {
        // Map to store Roman numerals and their integer values.
        Map<Character, Integer> m = new HashMap<>();
        m.put('I', 1);
        m.put('V', 5);
        m.put('X', 10);
        m.put('L', 50);
        m.put('C', 100);
        m.put('D', 500);
        m.put('M', 1000);
        
        int total = 0;
        // Initialize total with the value of the last character.
        total = m.get(s.charAt(s.length() - 1));
        
        // Iterate from the second-to-last character to the beginning.
        for (int i = s.length() - 2; i >= 0; i--) {
            // If the value of the current character is less than the value of the character to its right,
            // it's a subtractive case (like IV, IX).
            if (m.get(s.charAt(i)) < m.get(s.charAt(i + 1))) {
                total -= m.get(s.charAt(i));
            } else {
                // Otherwise, it's an additive case.
                total += m.get(s.charAt(i));
            }
        }
        
        return total;
    }
}

Roman to Integer in C++

class Solution {
public:
    int romanToInt(string s) {
        // Map to store Roman numerals and their integer values.
        std::unordered_map<char, int> m = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };
        
        int total = 0;
        // Initialize total with the value of the last character.
        total = m[s.back()];

        // Iterate from the second-to-last character to the beginning.
        for (int i = s.length() - 2; i >= 0; --i) {
            // If the value of the current character is less than the value of the character to its right,
            // it's a subtractive case (like IV, IX).
            if (m[s[i]] < m[s[i+1]]) {
                total -= m[s[i]];
            } else {
                // Otherwise, it's an additive case.
                total += m[s[i]];
            }
        }
        
        return total;
    }
};

Roman to Integer in TypeScript

function romanToInt(s: string): number {
    // Map to store Roman numerals and their integer values.
    const m: { [key: string]: number } = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    };
    
    let total = 0;
    // Initialize total with the value of the last character.
    total = m[s[s.length - 1]];
    
    // Iterate from the second-to-last character to the beginning.
    for (let i = s.length - 2; i >= 0; i--) {
        // If the value of the current character is less than the value of the character to its right,
        // it's a subtractive case (like IV, IX).
        if (m[s[i]] < m[s[i+1]]) {
            total -= m[s[i]];
        } else {
            // Otherwise, it's an additive case.
            total += m[s[i]];
        }
    }
    
    return total;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.