Problem:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Related Knowledge:
Roman Numbers:
I (1)
V (5)
X (10)
L (50)
C (100)
D (500)
M (1000)
Method:
The tricky is how to prepare the array. Consider there are totally 13 characters in roman number.
String[] str = {“M”,”CM”,”D”,”CD”,”C”,”XC”,”L”,”XL”,”X”,”IX”,”V”,”IV”,”I”};
int[] digit = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
Code:
public class Solution {
public String intToRoman(int num) {
String[] str = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int[] n = {1000,900,500,400,100,90,50,40,10,9,5,4,1 };
StringBuilder s = new StringBuilder();
for (int i = 0; i < str.length; i++){
int repeat = num/n[i];
for (; repeat >0; repeat--){
s.append(str[i]);
}
num = num % n[i];
}
return new String(s);
}
}
Method 2:
Get all digits into an ArrayList (Only 4 digits, since all < 3999). And then get one digit, append several strings.
1-3: use ‘one’
4: one + five
5: five
6-8: five +one
9: one + ten
The above rules apply for all 4 digits.
Code for method 2:
public class Solution {
public String intToRoman(int num) {
ArrayList<Integer> res = new ArrayList<Integer>();
int digit = 1000;
while (digit > 0){
res.add(num/digit);
num = num % digit;
digit = digit / 10;
}
StringBuilder s = new StringBuilder();
s.append(convert(res.get(0),"M","",""));
s.append(convert(res.get(1),"C","D","M"));
s.append(convert(res.get(2),"X","L","C"));
s.append(convert(res.get(3),"I","V","X"));
return s.toString();
}
public String convert(int digit, String one, String five, String ten){
switch (digit){
case 0: break;
case 1: return one;
case 2: return one.concat(one);
case 3: return one.concat(one).concat(one);
case 4: return one.concat(five);
case 5: return five;
case 6: return five.concat(one);
case 7: return five.concat(one).concat(one);
case 8: return five.concat(one).concat(one).concat(one);
case 9: return one.concat(ten);
}
return "";
}
}