[LeetCode/TS] 13. Roman to Integer

2024. 12. 27. 13:20· 코딩테스트

문제

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
'코딩테스트' 카테고리의 다른 글
  • [LeetCode/TS] 20. Valid Parentheses
  • [Leetcode/TS] 9. Palindrome Number
  • [Leetcode/TS] 2. Add Tow Number
  • [Leetcode/TS] 1. Two Sum
다시은
다시은
🔥
다시은
재은로그
다시은
전체
오늘
어제
  • 분류 전체보기 (127)
    • 코딩테스트 (40)
    • Language (2)
      • JAVA (2)
      • Kotlin (0)
      • TypeScript (0)
    • SQL (1)
    • 인프라 (1)
    • 왕초보일지 (77)
    • 회고 (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • sql
  • 스프레드시트
  • googleapis
  • 문자열변환
  • SQL문법
  • mysql
  • Kotlin

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
다시은
[LeetCode/TS] 13. Roman to Integer
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.