본문 바로가기

리트코드/easy

[리트코드] 13. Roman to Integer - js

반응형

1. 문제

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

 

Roman to Integer - LeetCode

Can you solve this real interview question? Roman to Integer - Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, 2 is written as II in Roman numeral, just tw

leetcode.com

2. 코드

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let result = 0;

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

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

        if (cur < next) {
            result += next - cur;
            i++;
        } else {
            result += cur;
        }
    }

    return result;
};
반응형