package day04;
public class IntToRoman {
public static void main ( String[ ] args) {
int num = 1994 ;
String res = intToRomanByGreedy ( num) ;
System. out. println ( res) ;
}
public static String intToRoman ( int num) {
char [ ] chars = { 'I' , 'V' , 'X' , 'L' , 'C' , 'D' , 'M' } ;
int base = 0 ;
String res = "" ;
while ( num != 0 ) {
int temp = num % 10 ;
num /= 10 ;
String tmp = getRoman ( temp, base, chars) ;
res = tmp + res;
base += 2 ;
}
return res;
}
public static String getRoman ( int i, int base, char [ ] chars) {
StringBuffer sb = new StringBuffer ( ) ;
if ( i <= 3 ) {
for ( int j = 0 ; j < i; j++ ) {
sb. append ( chars[ base] ) ;
}
return sb. toString ( ) ;
} else if ( i == 4 ) {
String tmp = "" + chars[ base] + chars[ base + 1 ] ;
return tmp;
} else if ( i >= 5 && i <= 8 ) {
sb. append ( chars[ base + 1 ] ) ;
for ( int j = i - 5 ; j >= 1 ; j -- ) {
sb. append ( chars[ base] ) ;
}
return sb. toString ( ) ;
} else {
return "" + chars[ base] + chars[ base + 2 ] ;
}
}
public static String intToRomanByGreedy ( int num) {
int [ ] values = { 1000 , 900 , 500 , 400 , 100 , 90 , 50 , 40 , 10 , 9 , 5 , 4 , 1 } ;
String [ ] symbols = { "M" , "CM" , "D" , "CD" , "C" , "XC" , "L" , "XL" , "X" , "IX" , "V" , "IV" , "I" } ;
StringBuilder stringBuilder = new StringBuilder ( ) ;
for ( int i = 0 ; i < values. length && num >= 0 ; i++ ) {
while ( values[ i] <= num) {
num -= values[ i] ;
stringBuilder. append ( symbols[ i] ) ;
}
}
return stringBuilder. toString ( ) ;
}
public static String intToRomanByCoding ( int num) {
String[ ] thousands = { "" , "M" , "MM" , "MMM" } ;
String[ ] hundreds = { "" , "C" , "CC" , "CCC" , "CD" , "D" , "DC" , "DCC" , "DCCC" , "CM" } ;
String[ ] tens = { "" , "X" , "XX" , "XXX" , "XL" , "L" , "LX" , "LXX" , "LXXX" , "XC" } ;
String[ ] ones = { "" , "I" , "II" , "III" , "IV" , "V" , "VI" , "VII" , "VIII" , "IX" } ;
return thousands[ num / 1000 ] + hundreds[ num % 1000 / 100 ] + tens[ num % 100 / 10 ] + ones[ num % 10 ] ;
}
}