LeetCode(12):整数转罗马数字
介绍

题解
一
class Solution {
public String intToRoman(int num) {
HashMap<Integer,String> hm = new HashMap<>();
hm.put(1000,"M");
hm.put(900,"CM");
hm.put(500,"D");
hm.put(400,"CD");
hm.put(100,"C");
hm.put(90,"XC");
hm.put(50,"L");
hm.put(40,"XL");
hm.put(10,"X");
hm.put(9,"IX");
hm.put(5,"V");
hm.put(4,"IV");
hm.put(1,"I");
int temp = num;
int index = 1;
StringBuffer sb = new StringBuffer();
while(temp>0){
int bit = temp%10;
if(bit<4){
while(bit-->0){
sb.insert(0,hm.get(index));
}
}else if(bit == 4){
sb.insert(0,hm.get(4*index));
}else if(bit == 9){
sb.insert(0,hm.get(9*index));
}else{
bit = bit -5;
while(bit-->0){
sb.insert(0,hm.get(index));
}
sb.insert(0,hm.get(5*index));
}
index = index * 10;
temp = temp /10;
}
return sb.toString();
}
}
二
class Solution {
public String intToRoman(int num) {
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuffer s = new StringBuffer();
for(int i =0;i<values.length;i++){
while(num>=values[i]){
s.append(symbols[i]);
num -= values[i];
}
}
return s.toString();
}
}