Leetcode – 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…


This content originally appeared on DEV Community and was authored by Rakesh Reddy Peddamallu

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


This content originally appeared on DEV Community and was authored by Rakesh Reddy Peddamallu


Print Share Comment Cite Upload Translate Updates
APA

Rakesh Reddy Peddamallu | Sciencx (2025-02-26T05:29:57+00:00) Leetcode – Roman to Integer. Retrieved from https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/

MLA
" » Leetcode – Roman to Integer." Rakesh Reddy Peddamallu | Sciencx - Wednesday February 26, 2025, https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/
HARVARD
Rakesh Reddy Peddamallu | Sciencx Wednesday February 26, 2025 » Leetcode – Roman to Integer., viewed ,<https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/>
VANCOUVER
Rakesh Reddy Peddamallu | Sciencx - » Leetcode – Roman to Integer. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/
CHICAGO
" » Leetcode – Roman to Integer." Rakesh Reddy Peddamallu | Sciencx - Accessed . https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/
IEEE
" » Leetcode – Roman to Integer." Rakesh Reddy Peddamallu | Sciencx [Online]. Available: https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/. [Accessed: ]
rf:citation
» Leetcode – Roman to Integer | Rakesh Reddy Peddamallu | Sciencx | https://www.scien.cx/2025/02/26/leetcode-roman-to-integer/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.