13. Roman to Integer


Problem

https://leetcode.com/problems/roman-to-integer/

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Notation Number
IV 4
IX 9
XL 40
XC 90
CD 400
CM 900
  • just need to take care of the second form
  • didn't check the validity of inputs because they are guaranteed
  • if you need to check just make sure they are following "thousands -> hundreds -> tens -> units"
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let result = 0
    s = s.toUpperCase()

    for (i = 0; i < s.length; i += 1) {
        switch(s[i]) {
            case 'M': result += 1000; break
            case 'D': result += 500; break
            case 'L': result += 50; break
            case 'V': result += 5; break
            case 'C': 
                if (s[++i] === 'M') {
                    result += 900
                } else if (s[i] === 'D') {
                    result += 400
                } else {
                    i -= 1
                    result += 100
                }
                break
            case 'X': 
                if (s[++i] === 'C') {
                    result += 90
                } else if (s[i] === 'L') {
                    result += 40
                } else {
                    i -= 1
                    result += 10
                }
                break
            case 'I': 
                if (s[++i] === 'X') {
                    result += 9
                } else if (s[i] === 'V') {
                    result += 4
                } else {
                    i -= 1
                    result += 1
                }
                break
            default: return NaN
        }
    }

    if (result >= 1 && result <= 3999) {
        return result
    }

    return NaN
};

results matching ""

    No results matching ""