[Link] https://leetcode.com/problems/integer-to-roman/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public String intToRoman(int num) {
int[] arr = new int[4]; // 0 : 1st digit 1: 2st ...
StringBuilder s = new StringBuilder();
for(int i = 0; i < 4; i++) {
int digit = num % 10;
num /= 10;
arr[i] = digit;
}
if(arr[3] != 0) {
s.append("M".repeat(arr[3]));
} if(arr[2]!=0) {
if(arr[2] == 4) s.append("CD");
else if(arr[2] == 9) s.append("CM");
else {
if(arr[2] >= 5) {
s.append("D");
arr[2] -= 5;
}
s.append("C".repeat(arr[2]));
}
} if(arr[1]!=0) {
if(arr[1] == 4) s.append("XL");
else if(arr[1] == 9) s.append("XC");
else {
if(arr[1] >= 5) {
s.append("L");
arr[1] -= 5;
}
s.append("X".repeat(arr[1]));
}
} if(arr[0]!=0) {
if(arr[0] == 4) s.append("IV");
else if(arr[0] == 9) s.append("IX");
else {
if(arr[0] >= 5) {
s.append("V");
arr[0] -= 5;
}
s.append("I".repeat(arr[0]));
}
}
return s.toString();
}
}