Edu./Leetcode

13. Roman to Integer

hotpotato0 2021. 7. 29. 00:08

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

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

Given a roman numeral, convert it to an integer.

 

해결방법 🚩

1. char 배열, int 배열을 선언하여 Input - char c에 따른 return Int 함수 구현

2. String 길이만큼 for문 이때 마지막에 도달한 로마자는 무조건 +

3. 다음 Roma 문자가 현재꺼보다 크면 -, 작으면 +

 

class Solution {
    public int romanToInt(String s) {
        int result = 0;
        
        for ( int idx = 0 ; idx < s.length() ; idx++ ){
            char c = s.charAt(idx);
            int num = getRomanToInt(c);
            
            if( idx + 1 == s.length()){
                result += num;
                continue;
            }
            char next = s.charAt(idx + 1);
            
            if ( num < getRomanToInt(next))
                result -= num;
            else
                result += num;
        }
        return result;

    }
    public int getRomanToInt(char c){
        char[] checkString = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
        int[] string_value = {1000, 500, 100, 50, 10, 5, 1};
        
        for( int idx = 0 ; idx < checkString.length ; idx++ ){
            if( c == checkString[idx] )
                return string_value[idx];
        }
        return 0;
    }
}

'Edu. > Leetcode' 카테고리의 다른 글

112. Path Sum  (0) 2021.08.02
21. Merge Two Sorted Lists  (0) 2021.07.27