Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
这道题我是考虑10进制左移运算,求出各个位的值,然后用查表法来构造字符串,其中0用“”来代替。
public class Solution {
public String intToRoman(int a) {
StringBuilder strBuilder = new StringBuilder();
String[] units =new String[]{"","I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
String[] tens = new String[]{"","X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] hundreds = new String[]{"","C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] thounsands = new String[]{"","M", "MM", "MMM"};
List<String[]> digits = new ArrayList<>();
digits.add(units);
digits.add(tens);
digits.add(hundreds);
digits.add(thounsands);
int temp;
int i = 0;
Stack<String> stack = new Stack<>();
while(a!=0){
temp = a%10;
stack.push(digits.get(i)[temp]);
a = a/10;
i++;
}
while(!stack.isEmpty()){
strBuilder.append(stack.pop());
}
return strBuilder.toString();
}
}
在论坛上看到有更加精简的代码
public static String intToRoman(int num) {
String M[] = {"", "M", "MM", "MMM"};
String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
类似于5进制的
int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuilder sb = new StringBuilder();
for(int i=0;i<values.length;i++) {
while(num >= values[i]) {
num -= values[i];
sb.append(strs[i]);
}
}
return sb.toString();
}