[leetcode] Roman to Integer

Spark Kim·2021년 10월 16일
0

leetcode

목록 보기
3/9

주어진 로마숫자 문자열을 정수로 변환하는 문제이다.
이때 각각의 로마숫자는 다음과 같은 값을 의미한다.

로마숫자숫자
I1
V5
X10
L50
C100
D500
M1000

그리고 문제상으로 보면 아래와 같은 조건이 있다.
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.

즉, VII 가 7이고, IV 가 4인 것처럼, 작은 숫자가 큰 숫자 앞에 올 경우 빼기로 작용한다는 조건을 의미한다.
예를 들면 LX 은 60이지만, XL 는 40으로 읽을 수 있다.

이 문제에 대해서는 HashMap에 각각의 문자가 의미하는 숫자를 맵핑하고, 앞 로마숫자가 뒤 로마문자보다 큰 경우, 작은 경우에 따라서 부호를 변경하여 더해주는 형식으로 문제를 풀이하였다.

class Solution {
    public int romanToInt(String s) {
        Map<String, Integer> romans = new HashMap<>();
        
        romans.put("I", 1);
        romans.put("V", 5);
        romans.put("X", 10);
        romans.put("L", 50);
        romans.put("C", 100);
        romans.put("D", 500);
        romans.put("M", 1000);
        
        String[] strs = s.split("");
        int result = romans.get(strs[strs.length-1]);
        int sign = 1;
        for(int i = strs.length-1; i>0; i--) {
            int now = romans.get(strs[i]);
            int next = romans.get(strs[i-1]);
            if(now > next) {
                sign = -1;
            } else if(now < next) {
                sign = 1;
            }
            result+=next*sign;
        }
        
        return result;
    }
}
profile
성장 지향 백엔드 개발자

0개의 댓글