문제
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 ones 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.
해결방법
function romanToInt(s: string): number {
let sum = 0;
const symbols = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
for (let i = 0; i < s.length; i++) {
const isI = s[i] === 'I' && (s[i + 1] === 'V' || s[i + 1] === 'X');
const isX = s[i] === 'X' && (s[i + 1] === 'L' || s[i + 1] === 'C');
const isC = s[i] === 'C' && (s[i + 1] === 'D' || s[i + 1] === 'M');
if (isI || isX || isC) {
sum += (symbols[s[i + 1]] - symbols[s[i]]);
i++;
} else {
sum += symbols[s[i]];
}
}
return sum;
};
결과
// 개선버전
// 심플하게 생각할 수 있었는데, 너무 어렵게 생각했다...
function romanToInt(s: string): number {
const symbols = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
};
let value = 0;
for(let i = 0; i < s.length; i+=1){
symbols[s[i]] < symbols[s[i+1]] ? value -= symbols[s[i]]: value += symbols[s[i]]
}
return value
};
'알고리즘' 카테고리의 다른 글
[LeetCode] 20. Valid Parentheses | 자바스크립트 (0) | 2022.09.10 |
---|---|
[LeetCode] 14. Longest Common Prefix | 자바스크립트 (0) | 2022.09.08 |
[LeetCode] 1. Two Sum | 자바스크립트 (0) | 2022.08.31 |
자바스크립트 문자열 내림차순 정렬하는 방법 (Sorting strings in descending order in Javascript) (0) | 2021.08.10 |
이 포스팅은 쿠팡파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.