J 크 2022. 10. 13. 00:21
728x90
반응형

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

 

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

 

 퇴근 하고 운동하구, 코드 공부를 새롭게 시작해보기 위해서 릿코드 사이트를 시작하고 가입을 하고 시키는 대로 버튼을 이것 저것 눌러보다가 쉬워 보여서 풀었는데, 아니었습니다. 생각보다 시간이 오래걸리네요. 

 문제의 핵심은 간단합니다. 

It's not hard to find the main point.

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

위와 같이 로마 숫자를 아라비안 숫자로 바꿔주는 것인데 아래의 규칙을 지켜야 합니다.

We can change Roman to Integer by using this table. And we must follow the rules.

 

▶  로마 숫자는 왼쪽부터 큰 숫자에서 작은 숫자로 작성되며 예외는 아래와 같습니다.

▶  V, X 앞에 I가 올 경우 I를 빼주어 4와 9가 됩니다.

▶  L,C 앞에 X가 올 경우 X를 빼주어 40과 90이 됩니다.

▶  D,M 앞에 C가 올 경우 C를 빼주어 400과 900이 됩니다.

 

▶  Roman numerals are written largest to smallest from left to right.

▶  If 'I' placed before 'V' or 'X', They become 'V' sub 'I' or 'X' sub 'I' and it means 4 or 9.

 If 'X' placed before  'L' or 'C', They become 'L' sub 'X' or 'C' sub 'X' and it means 40 or 90.

 If 'C' placed before  'D' or 'M', They become 'D' sub 'C' or 'M' sub 'C' and it means 400 or 900.

 

 저는 위의 규칙들을 활용하여 if문과 for문만으로도 풀어보고 ( 저는 C++ 언어를 사용합니다. )  다른 분들이 푸신 것을 본 후, 더욱 더 다양한 방법이 있다는 것을 깨닫고, map을 활용하여 다시 한 번 풀어보았습니다.

 I follwed rules and only used if/else and for loop to solved it first ( I'm using C++ ). But After saw another solutions, I solved the problem one more with STL map.

class Solution {
public:
	int romanToInt(string s) {

		if(s.size() < 1 || s.size() > 15)
			return 0;

		int nResult = 0;

		map<char, int> mapRomanToInt;

		mapRomanToInt.insert({ 'M', 1000 });
		mapRomanToInt.insert({ 'D', 500 });
		mapRomanToInt.insert({ 'C', 100 });
		mapRomanToInt.insert({ 'L', 50 });
		mapRomanToInt.insert({ 'X', 10 });
		mapRomanToInt.insert({ 'V', 5 });
		mapRomanToInt.insert({ 'I', 1 });

		for (int i = 0; i < s.size(); i++) {
			if((i != s.size() - 1) &&
					(mapRomanToInt.find(s[i])->second < mapRomanToInt.find(s[i + 1])->second)) {
				nResult += mapRomanToInt.find(s[i + 1])->second - mapRomanToInt.find(s[i])->second;
                            i++;
			}
			else
				nResult += mapRomanToInt.find(s[i])->second;
		}

		return nResult;
	}
};

 

 map으로 로마 숫자 - 아라바이 숫자 테이블 대로 값을 넣어주고, 예외의 6가지 상황은 유일하게 왼쪽에 있는 로마 숫자가 오른쪽에 숫자보다 작다는 조건과 이를 만족한다면 해당 로마숫자는 오른쪽에서 왼쪽을 뺀 숫자의 값으로 대입된다는 점을 활용하여 조건문을 작성하였습니다.

읽어주셔서 감사합니다 :)