문제
로마 숫자는 일곱 가지 기호로 표시됩니다 : I
, V
, X
, L
, C
, D
와 M
.
입력받은 로마 숫자를 정수로 변환해서 리턴하는 문제입니다.
답
|
|
설명
우선 제가 생각한 방법은 로마 숫자의 기본 값들은 json
변수에 저장하고,
규칙대로 코드를 짜봤습니다.
###규칙
- 로마 숫자는 큰수에서 작은수로 만들어진다.
- 작은수에서 큰수 순서로 적을 때는 큰수 - 작은수이다.
ex) IV = 5 - 1 = 4
입력 받은 문자열에서 문자 하나씩 가져와서 정수로 변환하고,
이전에 가져왔던 정수보다 작다면 계속 더하고, 크다면 이전의 정수를 빼고, 현재 정수를 더 합니다.
example
INPUT
MCMXCIV
M: +1000
여기서 result = 1000C: +100
여기서 result = 1000 + 100 = 1100M: +1000
여기서 이전 값인C
(+100) 보다M
(+1000)이 크기 때문에 2번 규칙에 따라 result = 1100 + 1000 - (2 * 100) = 1900X: +10
여기서 result = 1900 + 10 = 1910C: +100
여기서 이전 값인X
(+10)보다C
(+100)이 크기 때문에 2번 규칙에 따라 result = 1910 + 100 - (2 * 10) = 1990I: +1
여기서 result = 1990 + 1 = 1991V: +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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Example 5:
|
|
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].