Intger To Roman, intgertoroman
This refers to converting an integer Arabic number into a Roman number.
The idea is to place the roman numerals corresponding to 1-10 in the string array, and then find the data change pattern. For example: 389 = 300 + 89 + 9, the Roman numerals are corresponding to each other.
Public static void main (String [] args ){
String [] strs = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII ", "IX", "X "};
Wrote input = new partition (System. in );
System. out. print ("enter a 1-3999 INTEGER :");
Int n = input. nextInt ();
If (n <1 | n> 3999 ){
System. out. print ("the input is out of the range! ");
} Else {
String result = toRomanNumeral (strs, n );
System. out. println (result );
}
}
Public static String toRomanNumeral (String [] strs, int n ){
StringBuffer sb = new StringBuffer ();
If (n> 0 & n <= 10 ){
Sb. append (strs [n-1]);
} Else if (n> 10 & n <= 100 ){
Sb. append (zhuanHua (n/10, strs). append (strs [n % 10-1]);
} Else if (n> 100 & n <= 1000 ){
Sb. append (zhuanHua2 (n/100, strs). append (zhuanHua (n % 100/10, strs). append (strs [n % 100% 10-1]);
} Else if (n> 1000 & n <= 3999 ){
For (int I = 0; I <n/1000; ++ I ){
Sb. append ("M ");
}
N % = 1000;
Sb. append (zhuanHua2 (n/100, strs). append (zhuanHua (n % 100/10, strs). append (strs [n % 100% 10-1]);
} Else {
Sb. append ("the input is out of the range! ");
}
Return sb. toString ();
}
Public static String zhuanHua2 (int I, String [] strs ){
StringBuffer sb = new StringBuffer ();
For (int j = 0; j <strs [I-1]. length (); ++ j ){
Char temp = strs [I-1]. charAt (j );
If (temp = 'X '){
Temp = 'M ';
} Else if (temp = 'I '){
Temp = 'C ';
} Else if (temp = 'V '){
Temp = 'D ';
}
Sb. append (temp );
}
Return sb. toString ();
}
Public static String zhuanHua (int I, String [] strs ){
StringBuffer sb = new StringBuffer ();
For (int j = 0; j <strs [I-1]. length (); ++ j ){
Char temp = strs [I-1]. charAt (j );
If (temp = 'X '){
Temp = 'C ';
} Else if (temp = 'I '){
Temp = 'X ';
} Else if (temp = 'V '){
Temp = 'l ';
}
Sb. append (temp );
}
Return sb. toString ();
}