1. Question
Given an integer, convert it to a Roman number. The input is between 1 and 3999.
Several basic features of Roman numerals:
- I:1, V:5, X:10, l:50, c:100, d:500, m:1000
- Add: Numbers ligatures, small numbers to the right of large numbers
- Subtract: The small number is to the left of the large number
The limits of Roman numerals are characterized by:
- The digital ligatures is limited to I, X, C (i.e. 1,10,100) with a maximum of three;
- Decimal places on large number left only I, X, C
- Put a decimal on the left only the nearest that 1 Word class number: V, X left can only use I;l, C left only with X;d, M left can only use C
1 to 3999.
2. Solution
In turn, the number of a, ten, hundred, thousand corresponds to the corresponding representation of the Roman number, and then from the highest number of integers, followed by the table to take out the corresponding number of Roman representation, string accumulation can be.
Public classSolution {ArrayList< Hashmap<integer, string> >Romanvsint; Publicsolution () {initromanvsint (); } Public voidInitromanvsint () {Romanvsint=Newarraylist< hashmap< Integer, String > >(); HashMap< Integer, String > unit =Newhashmap< 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 tablehashmap< Integer, String > Ten =Newhashmap< 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 tablehashmap< Integer, String > Hundred =Newhashmap< 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 tablehashmap< Integer, String > thousand =Newhashmap< Integer, String >(); Thousand.put (1, "M"); Thousand.put (2, "MM"); Thousand.put (3, "MMM" ); Romanvsint.add (Thousand); //add the thousands ' digit transform table } PublicString Inttoroman (intnum) { int[] ToPart =New int[4]; intI=0; while(num!=0) {Topart[i+ +] = num%10; Num/= 10; } StringBuilder Res=NewStringBuilder (); for(i--; i>=0; i-- ){ if(Topart[i] = = 0)Continue; Res.append (Romanvsint.get (i). Get (Topart[i])); } returnres.tostring (); }}
View Code
Integer to Roman