loading...

Leetcode - Roman to Integer (with JavaScript)

urfan profile image Urfan Guliyev 惻2 min read

Today I am going to show how to solve the Leetcode Roman to Integer algorithm problem.

Here is the problem:
problem

There are seven symbols in the Roman numeral system. Iā€™m going to map each symbol to its value.

var romanToInt = function(s) {

    const sym = { 
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

}

I then create a new variable to represent the integer converted from a roman numeral.

var romanToInt = function(s) {

    const sym = { 
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

    let result = 0;

}

If the numerals are descending from left to right, largest to smallest, then they are added together. But if the numerals begin to ascend in order, then the larger number is subtracted by the preceding smaller number. For instance, in XVIV, X and V are added together to make 15. Because the I is followed by a larger number, V, it is subtracted from that number to make 4 and then added to the preceding XV to make 19.

Based on this rule, I will iterate from left to right. If the current symbol (cur) is less than the symbol to its right (next), then I will subtract the cur from the next and move 2 characters to the right. Otherwise, I will simply add them.

var romanToInt = function(s) {

    const sym = { 
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }

    let result = 0;

    for (i=0; i < s.length; i++){
        const cur = sym[s[i]];
        const next = sym[s[i+1]];

        if (cur < next){
            result += next - cur // IV -> 5 - 1 = 4
            i++
        } else {
            result += cur
        }
    }

    return result; 
};

Posted on by:

urfan profile

Urfan Guliyev

@urfan

Love coding, eating and travelling

Discussion

markdown guide