標籤:
1. Question
給定整數,將其轉化為羅馬數。輸入在1到3999之間。
羅馬數位幾個基本特點:
- I:1, V:5, X:10, L:50, C:100, D:500, M:1000
- 相加:數字連寫、小的數字在大的數字右邊
- 相減:小的數字在大的數字左邊
羅馬數位限制特點:
- 數字連寫僅限I, X, C(即1,10,100),且最多連用三個;
- 小數放在大數左邊僅限I, X, C
- 左邊放小數只能放最近的那個1字類數:V, X左邊只能用I;L, C左邊只能用X;D, M左邊只能用C
Given an integer, convert it to a roman numeral.Input is guaranteed to be within the range from 1 to 3999.
2. Solution
依次將個、十、百、千位的數字用相應的羅馬數對應表示,然後從整數的最高數位開始,依次對照表取出相應數位的羅馬錶示,字串累加即可。
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(); }}View Code
Integer to Roman