본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 13. Roman to Integer

반응형

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

간단 분기 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

각 symbol에 맞는 수를 반환하기 위한 map변수 symbolMap을 선언 후 초기화해줍니다.

📔 풀이과정

for loop를 수행하며 문자열 s를 확인해줍니다. 매 loop당 3 조건에 대해 고려해줍니다. 바로 다음 문자만 확인하면 되는 일정한 규칙이므로 간단히 if else문으로 처리해주면 됩니다.

  • 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.

1. 위 3조건 중 하나에 해당하면 해당 값을 ans에 누적해줍니다.

2. 아닌 경우 map으로 부터 문자에 대한 value값을 ans에 누적해 더해줍니다.

📔 정답출력

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
    map <char, int> symbolMap;
public:
    void initMap() {
        symbolMap['I'] = 1;
        symbolMap['V'] = 5;
        symbolMap['X'] = 10;
        symbolMap['L'] = 50;
        symbolMap['C'] = 100;
        symbolMap['D'] = 500;
        symbolMap['M'] = 1000;
    }
    int romanToInt(string s) {
        initMap();
        int ans = 0;
        for(int i = 0; i < s.size(); i++) {
            if(i != s.size() - 1) {
                if(s[i] == 'I') {
                    if(s[i+1] == 'V') { ans += 4; i++; continue;}
                    else if(s[i+1] == 'X') { ans += 9; i++; continue;}
                }
                if(s[i] == 'X') {
                    if(s[i+1] == 'L') { ans += 40; i++; continue;}
                    else if(s[i+1] == 'C') { ans += 90; i++; continue;}
                }
                if(s[i] == 'C') {
                    if(s[i+1] == 'D') { ans += 400; i++; continue;}
                    else if(s[i+1] == 'M') { ans += 900; i++; continue;}
                }
            }
            ans += symbolMap[s[i]];
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.