#11851: JAVA 參考解答


love203216 (pei)

學校 : 不指定學校
編號 : 64917
來源 : [27.242.160.248]
最後登入時間 :
2017-12-14 15:50:14
a013. 羅馬數字 -- NPSC 模擬試題 | From: [61.226.146.68] | 發表日期 : 2017-03-30 16:48

import java.util.*;
import java.math.*;
public class JAVA{
public static int toarnum(String s){
int num=0 ;
StringBuilder buffer = new StringBuilder(s);  //把s存入StringBuilder方便更改內容
for(int i=0;buffer.length()>0&&i<romannum.length;i++){
while(buffer.indexOf(romannum[i])==0){
num+=arnum[i]; //相當於num=arnum[i]+num; 
buffer.delete(0,romannum[i].length());
}
}
return num;

}
public static String toroman(int d){
String str="";
for(int i=0;i<arnum.length;i++){
while(d>=arnum[i]){
str+=romannum[i];
d-=arnum[i];
}
}
return str;
}

private final static String romannum[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
private final static int arnum[] ={1000,900,500,400,100,90,50,40,10,9,5,4,1};


public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String r_1;
String r_2;
String r_3;
int a=0,b=0,c=0;
while(sc.hasNext()){
r_1=sc.next();
if(r_1.charAt(0)=='#'){  //取r_1地一個位置的字元
break;
}
r_2=sc.next();
a=toarnum(r_1);
b=toarnum(r_2);
c=Math.abs(a-b);//取兩數絕對值
if(c==0){
System.out.println("ZERO");
}
r_3=toroman(c);
System.out.println(r_3);


}

}
}

 
ZeroJudge Forum