题目
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解题思路
从低位到高位分解数的每一位,然后用罗马字符串表示该位上的数,需要注意的是每次都从串头插入。
因为输入数据的取值范围很小,所以可以把每位上9个数的罗马串提前存起来。
代码
public class Solution {
public String intToRoman(int num)
{
String[][] table ={{"I","II","III","IV","V","VI","VII","VIII","IX"},
{"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"M","MM","MMM"}};
StringBuffer sb=new StringBuffer();
int n;
for(int i=0;num!=0;num/=10,++i)
{
n=num%10;
if(n!=0)
sb.insert(0,table[i][n-1]);
}
return sb.toString();
}
}
运行结果