这个题相对而言较为简单。正常思路是很好想的,无非是将整数取模,余数分别分配到各个字母对应的个数,特殊考虑4和9两种特殊情况。
public static String intToRoman(int num) { String result = ""; int oneI = 0, fiveV = 0,tenX = 0, fiftyL=0, hundredC=0, fivehundredD=0,thousandM=0; boolean I=false,X=false,C=false,I2=false,X2=false,C2=false; thousandM = num / 1000; fivehundredD = (num % 1000) / 500; if (num % 1000 >= 400 && num % 1000 < 500){ hundredC = 0; C = true; } else if(num % 1000 >= 900){ fivehundredD=0; C2=true; } else hundredC = (num % 500) / 100; fiftyL = (num % 100) / 50; if (num % 100 >= 40 && num % 100 < 50){ tenX = 0; X = true; } else if(num % 100 >= 90){ fiftyL=0; X2=true; } else tenX = (num % 50) / 10; fiveV = (num % 10) / 5; if (num % 10 == 4){ oneI = 0; I = true; } else if(num % 10 == 9){ fiveV=0; I2=true; } else oneI = num % 5; while (thousandM-- > 0) result += "M"; if (C) result += "CD"; else if(C2) result += "CM"; while (fivehundredD-- > 0) result += "D"; while (hundredC -- > 0) result += "C"; if(X) result += "XL"; else if(X2) result += "XC"; while (fiftyL-- > 0) result += "L"; while (tenX-- > 0) result += "X"; if(I) result += "IV"; else if(I2) result += "IX"; while (fiveV-- > 0) result += "V"; while (oneI-- > 0) result += "I"; return result; }
大致就是这个样子的,但是提交之后还是效率很低,所以想想办法提高一下效率,这让我想起了之前写的一个代码,根据月份求出相应月份的天数,乍一看是需要分情况讨论,需要用到switch或者是if之类的东西,但实际上,由于样本本来就小,像是月份只有12个,这个罗马数表示也是如此,所以我们可以自己建立一个词典用于查询。
这里给出M和C的词典:
通过词典我们可以快速的计算出整数所对应的罗马数字。
String M[] = {"", "M", "MM", "MMM"};
String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};