[LeetCode] 0013. Roman to Integer

Daniel·2024년 4월 24일
0

Algorithms(알고리즘)

목록 보기
4/7

문제

Roman numerals are represented by seven different symbols: IVXLCD and M.

SybolValue
I1
V5
X10
L50
C100
D500
M1000

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

input

s = "III"

output

3

Explanation

III = 3.


input

s = "LVIII"

output

58

Explanation

L = 50, V= 5, III = 3.


input

s = "MCMXCIV"

output

1994

Explanation

M = 1000, CM = 900, XC = 90 and IV = 4.


제약조건

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

문제 분석

로마숫자는 7가지로 표현된다.
왼쪽에서 오른쪽으로 가장 큰 숫자에서 가장 작은 숫자로 적습니다. -> 큰 숫자부터 나열 된다.

특정 조건에서 작은 수를 큰 수의 앞에 두어 두 수의 차를 나타낸다.
1. IV(5)와 X(10) 앞에 올 수 있습니다: IV (4), IX (9)
2. XL(50)과 C(100) 앞에 올 수 있습니다: XL (40), XC (90)
3. CD(500)과 M(1000) 앞에 올 수 있습니다: CD (400), CM (900)

손으로 풀어보기

위와 같이 손으로 풀어보았다.

추가로 생각할 점이 로마 숫자에 대응되는 수를 어떻게 관리할 것인가? 이였다.
Map을 사용하기로 했다.

슈도코드

pubilc int romanToInt(String s) {
	Map = (로마숫자,) 을 초기화
	total = 최종값이 저장 될 변수
	
	for(s의 길이 - 1 까지) {
		if(Map.get(현재문자) >= Map.get(다음문자)) {
			두 문자의 수를 더해 total에 합산한다.
		} else if(Map.get(현재문자) < Map.get(다음문자)) {
			total -= Map.get(현재문자)
		}
	}
	return total;
}

구현

class Solution {  
    public int romanToInt(String s) {  
        Map<Character, Integer> roman = new HashMap<>();  
		roman.put('I', 1);  
		roman.put('V', 5);  
		roman.put('X', 10);  
		roman.put('L', 50);  
		roman.put('C', 100);  
		roman.put('D', 500);  
		roman.put('M', 1000);  
		
		int total = 0;  
		
		for (int i = 0; i < s.length() - 1; i++) {  
			int curr = roman.get(s.charAt(i));  
			int prev = roman.get(s.charAt(i + 1));  
			if (curr >= prev) {  
				 total += curr;  
			} else {  
				 total -= curr;  
			}
		}  
		total += roman.get(s.charAt(s.length() - 1));  
		
		return total;  
}}

놓친부분

for 문에서 실수가 있었다.
1. 엣지 케이스를 고려하지 못함
2. 현재문자 >= 다음문자 일 때, total += 현재문자의 수 + 다음문자의 수 가 아니라 total += 현재문자의 수
3. 현재문자 < 다음문자 일 때, total -= 현재 문자의 수
4. 위 2, 3 번을 생각하지 못했다.

리펙토링

class Solution {
    public int romanToInt(String s) {
        // Initialize Roman numerals and their corresponding integer values
        Map<Character, Integer> roman = Map.of(
            'I', 1,   'V', 5,   'X', 10,  'L', 50,
            'C', 100, 'D', 500, 'M', 1000
        );
        
        int total = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            int current = roman.get(s.charAt(i));
            int next = roman.get(s.charAt(i + 1));
            if (current >= next) {
                total += current;
            } else {
                total -= current;
            }
        }
        
        total += roman.get(s.charAt(s.length() - 1));
        
        return total;
    }
}
profile
응애 나 애기 개발자

0개의 댓글