문제
https://leetcode.com/problems/roman-to-integer/description/
나열된 로마 숫자를 변환하는 문제
큰 수부터 작은 수로 나열되는게 기본인데 다음 수가 더 큰 수라면 마이너스를 하면 된다.
비교 대상은 딱 연속된 두 수뿐이라 순회하면서 크기 비교를 통해 더 작다면 +, 더 크다면 -
1.
function romanToInt(s: string): number {
const numbers = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
const array = s.split('');
let result = 0;
for (let i = 0; i < array.length; i++) {
const num = numbers[array[i]];
const nextNum = numbers[array[i+1]];
if (!nextNum) {
result += num
} else if (num >= nextNum) {
result += num
} else if (num < nextNum) {
result -= num
}
}
return result
};
2.
function romanToInt(s: string): number {
const numbers = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
const array = s.split('').map((s) => numbers[s])
let result = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] < array[i+1]) {
result -= array[i]
} else {
result += array[i]
}
}
return result
};
3. 다른 사람 풀이
const roman = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
};
function romanToInt(s: string): number {
const integers = s.split('').map(c => roman[c]);
return integers.reduce((acc, x, i) => x < integers[i+1] ? acc - x : acc + x, 0);
};
reduce 활용
4. 다른 사람 풀이
const RomanValues: {[numeral:string]: number} = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
const RomanPrefixes: {[numeral:keyof typeof RomanValues]: ReadonlySet<keyof typeof RomanValues>} = {
I: new Set(["V", "X"]),
X: new Set(["L", "C"]),
C: new Set(["D", "M"]),
}
function romanToInt(s: string): number {
let total = 0;
for(let i = 0; i < s.length - 1; i++){
const char = s[i];
if(char in RomanPrefixes && RomanPrefixes[char].has(s[i+1])) {
total -= RomanValues[char];
} else {
total += RomanValues[char];
}
}
return total + RomanValues[s[s.length - 1]];
};
덧셈, 뺄셈 되는 다음 수 기준을 미리 저장해두고
만약 1 다음 5나 10이 온다면 -
10 다음 50 이나 100 이 온다면 -
100 다음 500 이나 1000이 온다면 -
그 외에는 + 되도록
'코딩테스트' 카테고리의 다른 글
[LeetCode/TS] 20. Valid Parentheses (0) | 2024.12.30 |
---|---|
[Leetcode/TS] 9. Palindrome Number (1) | 2024.12.19 |
[Leetcode/TS] 2. Add Tow Number (0) | 2024.12.18 |
[Leetcode/TS] 1. Two Sum (1) | 2024.12.17 |
프로그래머스 | 레벨0 | Kotlin (0) | 2024.02.02 |