코딩테스트/Mastered

[leetcode] 13. Roman to Integer

스마일리 2022. 11. 4. 00:49

 

한 번에 통과!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    const romans = {
        I: 1,
        V: 5,
        X: 10,
        L: 50,
        C: 100,
        D: 500,
        M: 1000
    }
 
    let result = 0;
    for(let i = 0; i < s.length; i++){
        const currNum = romans[s[i]], nextNum = romans[s[i + 1]];
        if(currNum < nextNum){
            result += (nextNum - currNum)
            i++;
        }else{
            result += currNum;
        }
    }
 
    return result;
};
cs

문제에 나온 설명 그대로 따라서 풀었는데, 한 번 더 생각하면 더 쉬울 수 있었다.
아래는 문제 발췌

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: 

이렇게 다음 값보다 현재 값이 적으면 마이너스해주는 것이다. 굳이 인덱스를 두번 점프해주지 않아도 된다.

1
2
3
4
5
6
7
8
    for(let i = 0; i < s.length; i++){
        const currNum = romans[s[i]], nextNum = romans[s[i + 1]];
        if(currNum < nextNum){
            result -= currNum;
        }else{
            result += currNum;
        }
    }
cs