넘치게 채우기

[LeetCode] 13. Roman to Integer 본문

PS/LeetCode

[LeetCode] 13. Roman to Integer

riveroverflow 2023. 4. 26. 12:00
728x90
반응형
 

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

난이도 : Easy

 

문제

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.

 

로마 숫자를 정수로 변환하는 문제이다. 4를 로마 숫자로 표현하는 경우와 같이, I, X, C는 자신보다 더 큰 숫자 앞에서 빼는 용도로 쓰이니 주의해야 한다.

 

입력

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

문자열 s의 길이는 1부터 15까지이다.

s는 'I', 'V', 'X', 'L', 'C', 'D', 'M'으로만 구성된다.

수의 범위는 1에서 3999까지이다.

 

출력

로마 숫자를 정수로 변환한 값을 return 해주면 된다.

 

 

내가 생각해본 풀이

문자열을 순차적으로 탐색하며 switch ~ case문으로 분류하려는 플랜을 가져봤다.

뒤에 자신보다 더 큰 로마숫자가 있는 경우, 더하지 않고 빼서 IV와 같은 케이스를 처리하려 했다.

 

그러나, c++의 기본 STL인 unordered map을 이용하여 푸는 것이 더 깔끔하다.

 

코드(C++)

class Solution
{
public:
    int romanToInt(string s)
    {
        unordered_map<char, int> 	values = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };
        int num = 0;
        for (int i = 0; i < s.length(); i++)
        {
            if (i + 1 < s.length() && values[s[i]] < values[s[i + 1]])
            {
                num -= values[s[i]];
            }
            else
            {
                num += values[s[i]];
            }
        }
        return num;
    }
};
728x90
반응형

'PS > LeetCode' 카테고리의 다른 글

[LeetCode] 1137. N-th Tribonacci Number  (0) 2023.04.30
[LeetCode] 509. Fibonacci Number  (0) 2023.04.30
[LeetCode] 7. Reverse Integer  (0) 2023.04.30
[Leetcode] 134. Gas Station  (0) 2023.04.29
[LeetCode] 258. Add Digits  (0) 2023.04.27