12.Integer to Roman
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
拿到题目,分析,比较简单,除掉相应的基数单位,拼接起来就可以,不过要注意4,9这些特殊的表示。
先上我的代码吧;
public String intToRoman(int num){ StringBuffer sb=new StringBuffer(); while(num!=0){ if(num>=1000){ append(sb, "M", num/1000); num=num%1000; }else if(num>=500){ if(num>=900){ append(sb,"CM",1); num=num-900; }else{ append(sb,"D",num/500); num=num%500; } }else if(num>=100){ if(num>=400){ append(sb,"CD",1); num=num-400; }else{ append(sb,"C",num/100); num=num%100; } }else if(num>=50){ if(num>=90){ append(sb, "XC", 1); num=num-90; }else{ append(sb,"L",num/50); num=num%50; } }else if(num>=10){ if(num>=40){ append(sb,"XL",1); num=num-40; }else{ append(sb,"X",num/10); num=num%10; } }else if(num>=5){ if(num>=9){ append(sb,"IX",1); num=num-9; }else{ append(sb,"V",num/5); num=num%5; } }else{ if(num==4){ append(sb,"IV",1); num=num-4; }else{ append(sb,"I",num); num=0; } } } return sb.toString(); } public static void append(StringBuffer sb,String str,int times){ for(int i=0;i<times;i++){ sb.append(str); } }
但是呢,当我A掉之后,再去看这上面的第一个答案,跪了,又快又简单。用数组表示要放的数字。
public static String intToRoman(int num) { String M[] = {"", "M", "MM", "MMM"}; String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10]; }