Skip to content

Commit 1dd3324

Browse files
authored
[20260201] BOJ / G5 / 로마 숫자 / 이준희
1 parent 83b9248 commit 1dd3324

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static Map<Character, Integer> romanMap = new HashMap<>();
7+
8+
static int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
9+
static String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
10+
11+
public static void main(String[] args) throws IOException {
12+
initMap();
13+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
14+
15+
String s1 = br.readLine();
16+
String s2 = br.readLine();
17+
18+
int sum = romanToArab(s1) + romanToArab(s2);
19+
20+
System.out.println(sum);
21+
System.out.println(arabToRoman(sum));
22+
}
23+
24+
static void initMap() {
25+
romanMap.put('I', 1);
26+
romanMap.put('V', 5);
27+
romanMap.put('X', 10);
28+
romanMap.put('L', 50);
29+
romanMap.put('C', 100);
30+
romanMap.put('D', 500);
31+
romanMap.put('M', 1000);
32+
}
33+
34+
static int romanToArab(String s) {
35+
int total = 0;
36+
for (int i = 0; i < s.length(); i++) {
37+
int current = romanMap.get(s.charAt(i));
38+
39+
if (i + 1 < s.length() && current < romanMap.get(s.charAt(i + 1))) {
40+
total -= current;
41+
} else {
42+
total += current;
43+
}
44+
}
45+
return total;
46+
}
47+
48+
static String arabToRoman(int num) {
49+
StringBuilder sb = new StringBuilder();
50+
int i = 0;
51+
while (num > 0) {
52+
if (num >= values[i]) {
53+
sb.append(symbols[i]);
54+
num -= values[i];
55+
} else {
56+
i++;
57+
}
58+
}
59+
return sb.toString();
60+
}
61+
}
62+
```

0 commit comments

Comments
 (0)