LeetCode 12. LeetCode12-整数转罗马数字-20200608-java
原题链接
中等
作者:
bmdxyn0725
,
2020-06-08 16:02:40
,
所有人可见
,
阅读 543
组合各种情况,效率低下
class Solution {
public String intToRoman(int x) {
Map<Integer, String> dict = new HashMap();
dict.put(1, "I");
dict.put(2, "II");
dict.put(3, "III");
dict.put(4, "IV");
dict.put(5, "V");
dict.put(6, "VI");
dict.put(7, "VII");
dict.put(8, "VIII");
dict.put(9, "IX");
dict.put(10, "X");
dict.put(40, "XL");
dict.put(50, "L");
dict.put(90, "XC");
dict.put(100, "C");
dict.put(400, "CD");
dict.put(500, "D");
dict.put(900, "CM");
dict.put(1000, "M");
String res = "";
int high = 0;
while(x>0){
if(x/1000>0) {
high = x/1000;
while(high-->0) res += dict.get(1000);
x = x%1000;
}
if(x/100>0){
high = x/100;
if(high == 9) res += dict.get(900);
else if(high == 5) res += dict.get(500);
else if(high == 4) res += dict.get(400);
else {
if(high > 5) {
res += dict.get(500);
high -= 5;
}
while(high-->0){
res += dict.get(100);
}
}
x = x%100;
}
if(x/10>0){
high = x/10;
if(high == 9) res += dict.get(90);
else if(high == 5) res += dict.get(50);
else if(high == 4) res += dict.get(40);
else {
if(high > 5) {
res += dict.get(50);
high -= 5;
}
while(high-->0){
res += dict.get(10);
}
}
x = x%10;
}
if(x<10 && x>0){res += dict.get(x); x = x%x;}
}
return res;
}
}