Leetcode - Roman to Integer (with JavaScript)

urfan

Urfan Guliyev

Posted on May 25, 2020

Leetcode - Roman to Integer (with JavaScript)

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
    }

}


Enter fullscreen mode Exit fullscreen mode

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;

}


Enter fullscreen mode Exit fullscreen mode

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; 
};


Enter fullscreen mode Exit fullscreen mode
šŸ’– šŸ’Ŗ šŸ™… šŸš©
urfan
Urfan Guliyev

Posted on May 25, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related