LeetCode 13: Roman to Integer Solution

Master LeetCode problem 13 (Roman to Integer), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

13. Roman to Integer

Problem Explanation

Explanation:

To solve this problem, we can iterate through the input Roman numeral string from left to right. We will keep track of the value of the current symbol and compare it with the value of the next symbol. If the value of the current symbol is less than the value of the next symbol, we subtract the current symbol value from the total result. Otherwise, we add the current symbol value to the total result. By doing this, we handle the cases where subtraction is required in Roman numerals.

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input Roman numeral string.

Space Complexity:

The space complexity is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<>();
        map.put('I', 1);
        map.put('V', 5);
        map.put('X', 10);
        map.put('L', 50);
        map.put('C', 100);
        map.put('D', 500);
        map.put('M', 1000);
        
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            int value1 = map.get(s.charAt(i));
            if (i < s.length() - 1) {
                int value2 = map.get(s.charAt(i + 1));
                if (value1 < value2) {
                    result -= value1;
                } else {
                    result += value1;
                }
            } else {
                result += value1;
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 13 (Roman to Integer)?

This page provides optimized solutions for LeetCode problem 13 (Roman to Integer) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 13 (Roman to Integer)?

The time complexity for LeetCode 13 (Roman to Integer) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 13 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 13 in Java, C++, or Python.

Back to LeetCode Solutions