a013.
羅馬數字
--
NPSC 模擬試題
| From: [123.194.140.144] |
發表日期
:
2013-07-23 23:27
public class A013 {
public static void main ( String[] args ) {
Scanner scanner = new Scanner ( System.in );
String input1 , input2;
while ( ! ( input1 = scanner.next ( ) ).equals ( "#" ) ) {
input2 = scanner.next ( );
System.out.println ( toRome ( Math.abs ( toInt ( input1 ) - toInt ( input2 ) ) ) );
}
}
private static int toInt ( String s ) {
int result = 0;
int sLen = s.length ( );
for( int i=0 ; i < sLen ; i++ ) {
char nCh = ' ';
if ( i != sLen - 1 )
nCh = s.charAt ( i+1 );
switch ( s.charAt ( i ) ) {
case 'I' :
if ( nCh == 'I' || nCh == ' ' )
result += 1;
else
result -= 1;
break;
case 'V' :
result += 5;
break;
case 'X' :
if ( nCh == 'I' || nCh == 'V' || nCh == 'X' || nCh == ' ' )
result += 10;
else
result -= 10;
break;
case 'L' :
result += 50;
break;
case 'C' :
if ( nCh == 'M' || nCh == 'D' || nCh == ' ' )
result -= 100;
else
result += 100;
break;
case 'D' :
result += 500;
break;
case 'M' :
result += 1000;
break;
}
}
System.out.println ( result );
return result;
}
private static String toRome ( int n ) {
String result = "";
if ( n == 0 )
return "ZERO";
while ( n !=0 ) {
if ( n >= 1000 ) {
result += "M";
n -= 1000;
}
else if ( 1000 > n && n >= 900 ) {
result += "CM";
n -= 900;
}
else if ( 900 > n && n >= 500 ) {
result += "D";
n -= 500;
}
else if ( 500 > n && n >= 400 ) {
result += "CD";
n -= 400;
}
else if ( 400 > n && n>= 100 ) {
result += "C";
n -= 100;
}
else if ( 100 > n && n>= 90 ) {
result += "XC";
n -= 90;
}
else if ( 90 > n && n >= 50 ) {
result += "L";
n -= 50;
}
else if ( 50 > n && n >= 40 ) {
result += "XL";
n -= 40;
}
else if ( 40 > n && n >=10 ) {
result += "X";
n -= 10;
}
else if ( n == 9 ) {
result += "IX";
n -= 9;
}
else if ( 9 > n && n >= 5 ) {
result += "V";
n -= 5;
}
else if ( n == 4 ) {
result += "IV";
n -= 4;
}
else {
result += "I";
n -= 1;
}
}
System.out.println ( result );
return result;
}
}