题目:
给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。
示例:
输入: 1994
输出: "MCMXCIV"
解释: M = 1000, CM = 900, XC = 90, IV = 4.
代码:
public class Test8 {
public static void main(String[] args) {
String s = new Test8().intToRoman(1994);
System.out.println(s);
}
public String intToRoman(int num) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"I");
map.put(5,"V");
map.put(10,"X");
map.put(50,"L");
map.put(100,"C");
map.put(500,"D");
map.put(1000,"M");
StringBuilder result = new StringBuilder();
if (num/1000!=0) {
int temp = num/1000;
for (int i = 0; i < temp; i++) {
result.append(map.get(1000));
}
num = num%1000;
}
if (num/100!=0) {
int temp = num/100;
if(temp<4){
for (int i = 0; i < temp; i++) {
result.append(map.get(100));
}
}else if (temp==4){
result.append("CD");
}else if (temp>=5 && temp<9){
result.append(map.get(500));
for(int i = temp-5;i>0;i--){
result.append(map.get(100));
}
}else {
result.append("CM");
}
num = num%100;
}
if (num/10!=0) {
int temp = num/10;
if(temp<4){
for (int i = 0; i < temp; i++) {
result.append(map.get(10));
}
}else if (temp==4){
result.append("XL");
}else if (temp>=5 && temp<9){
result.append(map.get(50));
for(int i = temp-5;i>0;i--){
result.append(map.get(10));
}
}else {
result.append("XC");
}
num = num%10;
}
if (num/1!=0) {
int temp = num/1;
if(temp<4){
for (int i = 0; i < temp; i++) {
result.append(map.get(1));
}
}else if (temp==4){
result.append("IV");
}else if (temp>=5 && temp<9){
result.append(map.get(5));
for(int i = temp-5;i>0;i--){
result.append(map.get(1));
}
}else {
result.append("IX");
}
}
return result.toString();
}
}