DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

1 1 1

Leetcode - 13. Roman to Integer

Explanation
The trick is IV is 4 because , I which is 1 is less than V which is 5

so we check in the iteration , that if next number is greater than current , then we need to take difference , else we can just add the value of Roman symbol

Javascript Code

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function (s) {
    const RomanToIntmap = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    }
    let res = 0;
    for (let i = 0; i < s.length; i++) {

        let curr = RomanToIntmap[s[i]];
        let next = RomanToIntmap[s[i + 1]];

        if (next > curr && next !== undefined) {
            res += next - curr;
            i++;
        }
        else {
            res += curr;
        }
    }
    return res
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More