给定整数,将其转化为罗马数。输入在1到3999之间。
罗马数字的几个基本特点:
罗马数字的限制特点:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
依次将个、十、百、千位的数字用相应的罗马数对应表示,然后从整数的最高数位开始,依次对照表取出相应数位的罗马表示,字串累加即可。
public class Solution { ArrayList< HashMap<Integer, String> > romanVsInt; public Solution(){ initRomanVsInt(); } public void initRomanVsInt(){ romanVsInt = new ArrayList< HashMap< Integer, String > >(); HashMap< Integer, String > unit = new HashMap< Integer, String >(); unit.put( 1, "I" ); unit.put( 2, "II" ); unit.put( 3, "III" ); unit.put( 4, "IV" ); unit.put( 5, "V" ); unit.put( 6, "VI" ); unit.put( 7, "VII" ); unit.put( 8, "VIII" ); unit.put( 9, "IX" ); romanVsInt.add( unit ); //add the unit digit transform table HashMap< Integer, String > ten = new HashMap< Integer, String >(); ten.put( 1, "X" ); ten.put( 2, "XX" ); ten.put( 3, "XXX" ); ten.put( 4, "XL" ); ten.put( 5, "L" ); ten.put( 6, "LX" ); ten.put( 7, "LXX" ); ten.put( 8, "LXXX" ); ten.put( 9, "XC" ); romanVsInt.add( ten ); //add the ten‘ digit transform table HashMap< Integer, String > hundred = new HashMap< Integer, String >(); hundred.put( 1, "C" ); hundred.put( 2, "CC" ); hundred.put( 3, "CCC" ); hundred.put( 4, "CD" ); hundred.put( 5, "D" ); hundred.put( 6, "DC" ); hundred.put( 7, "DCC" ); hundred.put( 8, "DCCC" ); hundred.put( 9, "CM" ); romanVsInt.add( hundred ); //add the hundred‘ digit transform table HashMap< Integer, String > thousand = new HashMap< Integer, String >(); thousand.put( 1, "M"); thousand.put( 2, "MM"); thousand.put( 3, "MMM" ); romanVsInt.add( thousand ); //add the thousands‘ digit transform table } public String intToRoman( int num ){ int[] toPart = new int[4]; int i=0; while( num!=0 ){ toPart[i++] = num%10; num /= 10; } StringBuilder res = new StringBuilder(); for( i--; i>=0; i-- ){ if( toPart[i] == 0 ) continue; res.append( romanVsInt.get(i).get( toPart[i]) ); } return res.toString(); } }
原文:http://www.cnblogs.com/hf-cherish/p/4596367.html