본문 바로가기
공부 정리/LeetCode

[LeetCode] Roman to Integer (Javascript)

by 경적필패. 2021. 12. 17.
반응형

문제

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 one's 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.


문제[번역]

 

로마수는 7가지 심볼로 표현됩니다. I, V, X, L, C, D, M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

예를들면, 2는 II이며,

12는 XII (X + II),

27은 XXVII (X + V + II).\\로마수는 보통 큰값에서 작은값으로 왼쪽에서부터 오른쪽으로 씁니다.

그러나 4는 IIII가 아닙니다. 대신, 4는 IV를 사용합니다.

왜냐하면 4는 5에서 1을 빼도 되기때문입니다.

이런 원칙은 9에도 적용됩니다(IX)

다음에 6가지 빼기 예시가 있습니다.

  • 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.

로마수가 주어졌을때, 정수로 변환하시오.

 


 

Example 1

Input: s = "III"
Output: 3

Example 2

Input: s = "IV"
Output: 4

Example 3

 

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

 

 


제약조건

 

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

 


접근방법

일단 각 로마숫자에 대해 MAP를 만들어 해당 문자에 값을 저장합니다.

그 후, 입력받은 문자열에 대해 계산을 수행하는데,

현재 글자보다 다음 글자가 값이 더 크다면 결과값에서 빼주고, (IV => I는 V보다 작음)

현재 글자보다 다음 글자가 값이 더 작다면 결과값에서 더해줍니다.(VI => V는 I보다 큼)

 

 

 


코드

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let result = 0;
    const value = {
        "I" : 1,
        "V" : 5,
        "X" : 10,
        "L" : 50,
        "C" : 100,
        "D" : 500,
        "M" : 1000 
    }
    for(let i=0; i<s.length; i++){
        let current = value[s[i]];
        let next = value[s[i+1]];
        
        if(current < next) {
            result += next - current;
            i++;
        }
        else{
            result += current;
        }
    }
    return result;
};

 

 

 


주의사항

X

 

 

 

반응형

댓글