Skip to content

Commit 6428d58

Browse files
committed
add solution of problem 12: integer to roman
1 parent d6ba042 commit 6428d58

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

IntegerToRoman12/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Given an integer, convert it to a roman numeral.
2+
3+
Input is guaranteed to be within the range from 1 to 3999.

IntegerToRoman12/Solution.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
public String intToRoman(int num) {
3+
if (num < 1 || num > 3999)
4+
return "";
5+
6+
String[] map = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
7+
StringBuilder sb = new StringBuilder();
8+
int[] divisor = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
9+
int idx = 0;
10+
int mapSize = map.length;
11+
12+
while (idx < mapSize) {
13+
int cnt = num / divisor[idx];
14+
num %= divisor[idx];
15+
16+
for (int i = 0; i < cnt; i++)
17+
sb.append(map[idx]);
18+
19+
idx++;
20+
}
21+
22+
return sb.toString();
23+
}
24+
}

0 commit comments

Comments
 (0)