Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
先是了解罗马数的构成
基本字符 |
I
|
V
|
X
|
L
|
C
|
D
|
M
|
---|---|---|---|---|---|---|---|
相应的阿拉伯数字表示为 |
1
|
5
|
10
|
50
|
100
|
500
|
1000
|
从中不难发现规律:
千位数由M组成
百位数由M,D,C组成
十位数由C,L,X组成
个位数由X,V,I组成
然后代码如下
public String getStr(String str,int i,String s1,String s2,String s3){ switch(i){ case 1:str+=s3;break; case 2:str+=s3+s3;break; case 3:str+=s3+s3+s3;break; case 4:str+=s3+s2;break; case 5:str+=s2;break; case 6:str+=s2+s3;break; case 7:str+=s2+s3+s3;break; case 8:str+=s2+s3+s3+s3;break; case 9:str+=s3+s1;break; } return str; } public String intToRoman(int num) { int ge,shi,bai,qian; String string=""; if((qian=num/1000)!=0){ num=num%1000; switch(qian){ case 3:string+="MMM";break; case 2:string+="MM";break; case 1:string+="M"; } } if((bai=num/100)!=0){ num=num%100; string=getStr(string,bai,"M","D","C"); } if((shi=num/10)!=0){ num=num%10; string=getStr(string,shi,"C","L","X"); } if((ge=num)!=0){ string=getStr(string,ge,"X","V","I"); } return string; }