본문 바로가기

Leetcode 100문제 도전

[Leetcode 5/100] Roman to Integer - Easy

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

 

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 pre = RomanToInteger(s.charAt(s.length()-1));
        int answer = pre;
        
        for(int i=s.length()-2; i>=0; i--){
            int cur = RomanToInteger(s.charAt(i));
            
            if(cur < pre ){
                answer -= cur;
                pre = 0;
            } else {
                answer += cur;
                pre = cur;
            }
            
        }
        
        return answer;
        
    }
    
    public int RomanToInteger(char c){
        
        switch(c){
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
        }
        return 0;
    }
}