알고리즘

[LeetCode] 13. Roman to Integer | 자바스크립트

남양주개발자 2022. 9. 5. 22:52
728x90
반응형

[LeetCode] 13. 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 two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

해결방법

function romanToInt(s: string): number {
    let sum = 0;
    const symbols = {
        I: 1,
        V: 5,
        X: 10,
        L: 50,
        C: 100,
        D: 500,
        M: 1000
    }

    for (let i = 0; i < s.length; i++) {
        const isI = s[i] === 'I' && (s[i + 1] === 'V' || s[i + 1] === 'X');
        const isX = s[i] === 'X' && (s[i + 1] === 'L' || s[i + 1] === 'C');
        const isC = s[i] === 'C' && (s[i + 1] === 'D' || s[i + 1] === 'M');
        
        if (isI || isX || isC) {
            sum += (symbols[s[i + 1]] - symbols[s[i]]);
            i++;
        } else {
            sum += symbols[s[i]];
        }
    }
    
    return sum;
};

결과

퍼포먼스는 아쉬운..

// 개선버전
// 심플하게 생각할 수 있었는데, 너무 어렵게 생각했다...
function romanToInt(s: string): number {
    const symbols = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000
    };

    let value = 0;
    
    for(let i = 0; i < s.length; i+=1){
        symbols[s[i]] < symbols[s[i+1]] ? value -= symbols[s[i]]: value += symbols[s[i]]
    }
    
    return value
};
728x90
반응형
그리드형