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 |
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:
Given a roman numeral, convert it to an integer.
로마 숫자가 주어지면 정수로 변환하는 문제.
작은 값이 앞에 위치한 경우는 뒤의 값에서 앞의 값을 빼줘야 한다.
Input: s = "III"
Output: 3
Explanation: III = 3.
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
// Runtime: 182 ms, faster than 70.21%
// Memory Usage: 49.5 MB, less than 14.35%
var romanToInt = function(s) {
let num = 0;
const map = new Map();
map.set("I", 1)
.set("V", 5)
.set("X", 10)
.set("L", 50)
.set("C", 100)
.set("D", 500)
.set("M", 1000);
for (let i = 0; i < s.length; i++) {
if (map.get(s[i]) < map.get(s[i + 1])) {
num -= map.get(s[i]);
} else {
num += map.get(s[i]);
}
}
return num;
};
이번 문제는 대부분의 풀이가 변수명에만 차이가 있을 뿐 비슷비슷했다.