Notice
Recent Posts
Recent Comments
Link
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

eumjo_o

leetcode13 - Roman to Integer / Easy / TypeScript 본문

카테고리 없음

leetcode13 - Roman to Integer / Easy / TypeScript

eumjo_o 2023. 3. 31. 21:12

https://leetcode.com/problems/roman-to-integer/

 

Roman to Integer - LeetCode

Can you solve this real interview question? Roman to Integer - 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 tw

leetcode.com

Time Complexity O(N), Space Complexity O(1)

  • 문자열 길이만큼 순회하면서 Map에서 찾는다.
  • 4(IV), 9(IX), 40(XL), 90(XC), 400(CD), 900(CM) 등 4와 9가 들어가는 경우에는 앞의 문자가 뒤의 문자보다 작다.
  • 해당 경우를 이용하여 '앞의문자' < '뒤의문자' 인 경우 4(5-1), 9(10-1) 값으로 계산하도록 로직을 짠다.
const romanMap = { 
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
}

function romanToInt(s: string): number {
    let sum = 0;

    for(let i = 0; i < s.length; i++) {
        const currItem = romanMap[s[i]]
        const nextItem = romanMap[s[i+1]];

        if(currItem < nextItem) {
            sum += (nextItem - currItem);
            i++;
        } else {
            sum += currItem;
        }
    }

    return sum;
};