LeetCode - 13. Roman Integer(HashTable, Math, String)*

YAMAMAMO·2022년 11월 1일
0

LeetCode

목록 보기
76/100

문제

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

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

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

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

풀이

class Solution {
    public int romanToInt(String s) {
       int res=0, now=0, pre=0;
        
        for(int i=s.length()-1; i>=0; i--){
            switch(s.charAt(i)){
                case 'I' : now = 1; break;
                case 'V' : now = 5; break;
                case 'X' : now = 10; break;
                case 'L' : now = 50; break;
                case 'C' : now = 100; break;
                case 'D' : now = 500; break;
                case 'M' : now = 1000; break;
            }
            
            if(now<pre) res-=now;
            else res+=now;
            
            pre=now;
        }
        
        return res;
    }
}
profile
안드로이드 개발자

0개의 댓글