Skip to content

Commit c8433f6

Browse files
authored
Refactored Integer To Roman.java
1 parent 02c1c26 commit c8433f6

File tree

1 file changed

+12
-14
lines changed

1 file changed

+12
-14
lines changed

Medium/Integer To Roman.java

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

0 commit comments

Comments
 (0)