Leetcode – 13 – Roman to Integer

Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.


In this problem we have to convert the given roman numerals to integer.

Brute Force Logic:

The logic is simple and reverse of the Leetcode – 12 – Integer to Roman

We keep adding or subtracting the corresponding decimal value based o where the roman numerals is placed.

for eg.

for IV , we compare the first and  second character and determine if the value is less than or greater than 5. In this case I is less than V so we subtract 1 from 5 which is 4.

We will have a utility method to determine the Integer value for the corresponding roman value.



public class Solution {
    public int romanToInt(String s) {
        int result=0;
        if(s != null && !s.equals("")){
            int n = s.length();
            int i = 0;
            while(i <= n-1) {
                        return result + char2Number(s.charAt(i));
                    int n1 = char2Number(s.charAt(i));
                    int n2 = char2Number(s.charAt(i+1));
                    if(n1 < n2)
                        result = result - n1;
                        result = result + n1;
            return result;
    public int char2Number(char c){
                    case 'I':
                        return 1;
                    case 'V':
                        return 5;
                    case 'X':
                        return 10;
                    case 'L':
                        return 50;
                    case 'C':
                        return 100;
                    case 'D':
                        return 500;
                    case 'M':
                        return 1000;
                        return 0;

Time Complexity: O(n)

  • Go through all the roman numerals – O(n)

Space Complexity: O(1)

  • We will resulting integer digit one by one  – O(1)

Available Test Cases: 3999

  • handle for each unique roman characters



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: