본문 바로가기
LeetCode/코딩 테스트 스터디 3주차

[LeetCode] 12. Integer to Roman 풀이 (JS)

by inwoo1324 2022. 7. 24.

0. 문제

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

 

Integer to Roman - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

로마 숫자는 7가지 기호로 표시됩니다

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

로마 숫자는 일반적으로 왼쪽에서 오른쪽으로 큰 것에서 작은 것 순으로 표기한다. 하지만 아래 6가지의 경우 오른쪽에서 왼쪽으로 작은 것에서 큰 것으로 표기되며 빼기가 적용된다. (IV, IX, XL, XC, CD, CM)

  • IV(5)와 (10) 앞에 배치 X하여 4와 9을 만들 수 있다.
  • XL(50)과 (100) 앞에 배치 C하여 40과 90을 만들 수 있다.
  • CD(500)과 (1000) 앞에 배치 M하여 400과 900을 만들 수 있다.

정수가 주어지면 로마 숫자로 변환한다.

#1
Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 

#2
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

#3
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

let intToRoman = function(num) {
    let answer = '';
    let sH = new Map([
        [1000, 'M'],
        [900, 'CM'],
        [500, 'D'],
        [400, 'CD'],
        [100, 'C'],
        [90, 'XC'],
        [50, 'L'],
        [40, 'XL'],
        [10, 'X'],
        [9, 'IX'],
        [5, 'V'],
        [4, 'IV'],
        [1, 'I']
    ]);
    while (num !== 0) {
        for (let [key, value] of sH) {
            if (num >= key) {
                answer += value;
                num = num - key;
                break
            }
        }
    }
    return answer;
};
Runtime: 146 ms, faster than 84.02% of JavaScript online submissions for Integer to Roman.
Memory Usage: 49.4 MB, less than 26.15% of JavaScript online submissions for Integer to Roman.

 

Map = 모든 로마숫자를 내림차순으로 저장