#27202: Java 解題示範


s10914054@gm.cyut.edu.tw (Justin Tseng)

School : No School
ID : 167107
IP address : [125.224.98.163]
Last Login :
2021-10-12 08:59:35
a013. 羅馬數字 -- NPSC 模擬試題 | From: [111.250.7.53] | Post Date : 2021-09-18 14:00

有任何問題歡迎提問

第一個副程式 羅馬數字轉數字

第二個副程式 數字轉羅馬數字

以下為程式碼

 

 

 

import java.util.*;

 

public class a013

{

public static int ConvertToNumber(String roman)

{

int digit=0,sum=0;

 

HashMap<Character,Integer> number=new HashMap<Character,Integer>();

number.put('I',1);

number.put('V',5);

number.put('X',10);

number.put('L',50);

number.put('C',100);

number.put('D',500);

number.put('M',1000);

 

for(int i=0;i<roman.length();i++)

{

sum+=number.get(roman.charAt(i));

if(number.get(roman.charAt(i))>digit)

{

sum-=digit+digit;

}

digit=number.get(roman.charAt(i));

}

 

return sum;

}

public static String ConvertToRomanNumeral(int number)

{

String rnumber="";

String romans[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};

int numbers[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};

 

for(int i=0;i<romans.length;i++)

{

while(number>=numbers[i])

{

rnumber+=romans[i];

number-=numbers[i];

}

}

 

return rnumber;

}

public static void main(String[] args)

{

int difference,number1,number2;

 

Scanner sc=new Scanner(System.in);

while(sc.hasNext())

{

String rnumber1=sc.next();

if(rnumber1.equals("#"))

{

break;

}

String rnumber2=sc.next();

 

number1=ConvertToNumber(rnumber1);

number2=ConvertToNumber(rnumber2);

difference=Math.abs(number1-number2);

 

System.out.println(difference==0? "ZERO":ConvertToRomanNumeral(difference));

}

 

sc.close();

}

}

 
ZeroJudge Forum