题目描述:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:
注意到用例比较少,所以采用以空间换时间的方法,把所有的结果列出,然后组合出输入值n的字符串即可。
具体代码:
1 public class Solution { 2 public static String intToRoman(int num) { 3 String[][] array={ 4 {"","I","II","III","IV","V","VI","VII","VIII","IX"},//0-9 5 {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},//10-90 6 {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},//100-900 7 {"","M","MM","MMM"}//1000-3000 8 }; 9 StringBuilder sb = new StringBuilder(); 10 int n=num/1000; 11 sb.append(array[3][n]); 12 num=num%1000; 13 14 n=num/100; 15 sb.append(array[2][n]); 16 num=num%100; 17 18 n=num/10; 19 sb.append(array[1][n]); 20 num=num%10; 21 22 sb.append(array[0][num]); 23 24 return sb.toString(); 25 } 26 }