알고리즘 문제풀이/LeetCode

LeetCode 13번 - Roman to Integer

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 result = 0;
        for(int i=0; i<s.size(); i++){
            if(s.at(i) == 'I'){
                if(i != s.size()-1 && s.at(i+1) == 'V' ){
                    result += 4;
                    i++;
                }
                else if(i != s.size()-1 && s.at(i+1) == 'X' ){
                    result += 9;
                    i++;
                }
                else{
                    result += 1;
                }
            }   
            else if(s.at(i) == 'V'){
                result += 5;
            }
            else if(s.at(i) == 'X'){
                if(i != s.size()-1 && s.at(i+1) == 'L' ){
                    result += 40;
                    i++;
                }
                else if(i != s.size()-1 && s.at(i+1) == 'C' ){
                    result += 90;
                    i++;
                }
                else{
                    result += 10;
                }
            }
             else if(s.at(i) == 'L'){
                result += 50;
            }
              else if(s.at(i) == 'C'){
                if(i != s.size()-1 && s.at(i+1) == 'D' ){
                    result += 400;
                    i++;
                }
                else if(i != s.size()-1 && s.at(i+1) == 'M' ){
                    result += 900;
                    i++;
                }
                else{
                    result += 100;
                }
            }
             else if(s.at(i) == 'D'){
                result += 500;
            }
            else{
                result += 1000;
            }
            
        }
        
        return result;
    }
};