본문 바로가기
Programming Solve/Leetcode

리트코드(Leetcode) - Roman to Integer / C++

by msm1029 2021. 12. 1.
반응형

문제 링크 : 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

 

소스 코드

class Solution {
public:
    int romanToInt(string s) {
        int ret = 0;
        for(int i=0; i<s.size(); i++){
            if(s[i] == 'I'){
                if(s[i+1] == 'V'){
                    ret += 4;
                    i++;
                }
                else if(s[i+1] == 'X'){
                    ret += 9;
                    i++;
                }
                else ret += 1;
            }
            else if(s[i] == 'V') ret += 5;
            else if(s[i] == 'X'){
                if(s[i+1] == 'L'){
                    ret += 40;
                    i++;
                }
                else if(s[i+1] == 'C'){
                    ret += 90;
                    i++;
                }
                else ret += 10;
            }
            else if(s[i] == 'L') ret += 50;
            else if(s[i] == 'C'){
                if(s[i+1] == 'D'){
                    ret += 400;
                    i++;
                }
                else if(s[i+1] == 'M'){
                    ret += 900;
                    i++;
                }
                else ret += 100;
            }
            else if(s[i] == 'D') ret += 500;
            else ret += 1000;
        }
        
        return ret;
    }
};
반응형