알고리즘/LeetCode(easy)

13. Roman to Integer

SummerEda 2019. 12. 18. 10:51
LeetCode 영어 문제

 

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, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven 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. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III" Output: 3

Example 2:

Input: "IV" Output: 4

Example 3:

Input: "IX" Output: 9

Example 4:

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

Example 5:

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

 

번역

[로마숫자를 정수로 바꾸는 문제]

 

로마 숫자는 I, V, X, L, C, D 및 M의 7 가지 기호로 표시됩니다. 기호 값 I 1 V 5 X 10 L 50 C 100 D 500 M 1000

예를 들어, 두 개는 로마 숫자로 II로 표기되며 두 개만 더해집니다. 12 개는 XII로 작성되는데 이는 단순히 X + II입니다.

숫자 27은 XXVII로 쓰여지며 XX + V + II입니다. 로마 숫자는 일반적으로 왼쪽에서 오른쪽으로 가장 크거나 가장 작습니다.

그러나 4의 숫자는 IIII가 아닙니다. 대신, 숫자 4는 IV로 작성됩니다.

하나는 5 앞에 있기 때문에 우리는 4를 뺍니다. 같은 원칙이 9 번에 적용되며 IX로 작성됩니다.

빼기가 사용되는 6 가지 경우가 있습니다. V (5)와 X (10) 앞에 배치하여 4와 9를 만들 수 있습니다.

X는 L (50)과 C (100) 앞에 위치하여 40과 90을 만들 수 있습니다.

C는 D (500)와 M (1000) 앞에 위치하여 400과 900을 만들 수 있습니다. 로마 숫자가 주어지면 정수로 변환하십시오.

입력은 1-3999 범위 내에 있어야합니다.

예 1 : 입력 : "III"출력 : 3

예 2 : 입력 : "IV"출력 : 4

예 3 : 입력 : "IX"출력 : 9

예 4 : 입력 : "LVIII"출력 : 58 설명 : L = 50, V = 5, III = 3

예 5 : 입력 : "MCMXCIV"출력 : 1994 설명 : M = 1000, CM = 900, XC = 90 및 IV = 4

 

다른 사람의 풀이

1

class Solution {
    public int romanToInt(String s) {
        int result = 0;
        int temp = 0;
        int[] answer = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'I') answer[i] = 1;
            else if (s.charAt(i) == 'V') answer[i] = 5;
            else if (s.charAt(i) == 'X') answer[i] = 10;
            else if (s.charAt(i) == 'L') answer[i] = 50;
            else if (s.charAt(i) == 'C') answer[i] = 100;
            else if (s.charAt(i) == 'D') answer[i] = 500;
            else if (s.charAt(i) == 'M') answer[i] = 1000;   
        }
        for (int i = s.length()-1; i >= 0; i--) {
            if (answer[i] >= temp) result += answer[i];
            else result -= answer[i];
            temp = answer[i];
        }
        return result;
    } 
}

2

class Solution {
    public int romanToInt(String s) {
        int smallestVal = 1000;
        int total = 0;
        int current = 0;
        for (char c : s.toCharArray()) {
            if (c == 'M') {
                current = 1000;
            } else if (c == 'D') {
                current = 500;
            } else if (c == 'C') {
                current = 100;
            } else if (c == 'L') {
                current = 50;
            } else if (c == 'X') {
                current = 10;
            } else if (c == 'V') {
                current = 5;
            } else if (c == 'I') {
                current = 1;
            }
            if (current > smallestVal) current -= (2 * smallestVal);
            else if (current < smallestVal) smallestVal = current;
            total += current;
        }
        return total;
    }
}

3

문제는 어렵지 않은데 예외처리를 일일이 해줘야하는게 귀찮았음.

먼저 각각 문자가 뜻하는 숫자를 roman에 담고, 특별한 경우를 따로 special에 담는다.

우선 길이가 1개일 때 roman에서 매칭되는 값을 리턴해주고

길이가 2개 이상인 경우에는 먼저 special에 해당하는 문자가 있는지 찾아서 result에 더해준 뒤에 문자열에서 삭제해주는 포문을 하나 돌리고

남은 값들을 roman에서 매칭시켜 result에 더해주고 리턴하면 끝

객체로 묶는 생각을 바로 못해서 일일이 if문으로 했다가, 나중에 수정했음

const romanToInt = s => { 
	const roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000};
	if ( s.length === 1 ) {
	return roman[s] 
	} let result = 0; const special = { 
	'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900 
	} for ( let i = 0; i < s.length-1; i++ ) 
	{ if ( special[s[i]+s[i+1]] ) 
	{ result += special[s[i]+s[i+1]]; s = s.replace(s[i]+s[i+1], ''); i = -1 } } 
	for ( let j = 0; j < s.length; j++ ) {
    result += roman[s[j]] } return result };

 

풀이

 

for문을 통해 따로 sum 에 더해주는 방식으로 처리했다. 그리고 현재 문자가 다음 문자보다 작으면 오히려 빼주는데, 그렇게 하면 4내지는 9가 나오게 된다.

 

출처 sources
 

Roman to Integer - 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