[LeetCode] 13. Roman to Integer

#13. Roman to Integer

문제

로마 숫자는 일곱 가지 기호로 표시됩니다 : I, V, X, L, C, DM. 입력받은 로마 숫자를 정수로 변환해서 리턴하는 문제입니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
var romanToInt = function(s) {
    const romanNumerals = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    };
    
    let prev = 0;
    let result = 0;
    for(let i = 0; i<s.length; i++) {
        let current = romanNumerals[s[i]];
        if (prev > 0 && current > prev) result += - (prev * 2);
        result += current;
        prev = current;
    }
    return result;
};

설명

우선 제가 생각한 방법은 로마 숫자의 기본 값들은 json 변수에 저장하고, 규칙대로 코드를 짜봤습니다.

###규칙

  1. 로마 숫자는 큰수에서 작은수로 만들어진다.
  2. 작은수에서 큰수 순서로 적을 때는 큰수 - 작은수이다.

ex) IV = 5 - 1 = 4

입력 받은 문자열에서 문자 하나씩 가져와서 정수로 변환하고,

이전에 가져왔던 정수보다 작다면 계속 더하고, 크다면 이전의 정수를 빼고, 현재 정수를 더 합니다.

example

INPUT MCMXCIV

  1. M: +1000 여기서 result = 1000
  2. C: +100 여기서 result = 1000 + 100 = 1100
  3. M: +1000 여기서 이전 값인 C(+100) 보다 M(+1000)이 크기 때문에 2번 규칙에 따라 result = 1100 + 1000 - (2 * 100) = 1900
  4. X: +10 여기서 result = 1900 + 10 = 1910
  5. C: +100 여기서 이전 값인 X(+10)보다 C(+100)이 크기 때문에 2번 규칙에 따라 result = 1910 + 100 - (2 * 10) = 1990
  6. I: +1 여기서 result = 1990 + 1 = 1991
  7. V: +5 여기서 이전 값인 I(+1)보다 V(+5)이 크기 때문에 2번 규칙에 따라 result = 1991 + 5 - (2 * 1) = 1994 OUTPUT: 1994

LeetCode

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.

Example 1:

1
2
Input: s = "III"
Output: 3

Example 2:

1
2
Input: s = "IV"
Output: 4

Example 3:

1
2
Input: s = "IX"
Output: 9

Example 4:

1
2
3
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

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

Constraints:

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

Built with Hugo
Theme Stack designed by Jimmy