2016年5月11日 星期三

UVA 343: What Base Is This ?

Q343: What Base Is This ?

我們知道在一個數字中不同的位置其權重(weight)是不同的。例如10進位的數字362中,2的權重是100,6的權重是101,3的權重是102。所以這個數10進位的值=3*102+6*101+2*100。同樣的機制也適用於其他的進位制。然而362這個數字在9進位制或14進位制中所代表的值是和10進位制的362不同的。
在本問題中,給你2個數字(以X、Y代表),請你寫一個程式找出X最小是多少進位制,且Y最小是多少進位制,才能使X,Y代表相同的值。例如:給你12和5。若用10進位來看的話,這2個數明顯是不同的。但是假如你用3進位來看12,用6進位來看5呢?12(3進位)=1*31+2*30=5(10進位),而5(6進位)=5(10進位)。所以如果你選對進位制的話,12和5是可以代表相同的值的。
Input
每組測試資料一列,包含2個數字X、Y。X、Y可以2進位制到36進位制來看待。在表達上,0~9就代表0~9,A,B,C,......,Z則分別代表10,11,12,......,35
Output
每組測試資料輸出的一列,格式請參考Sample Output。請注意X、Y有可能在2進位制到36進位制中均無法使之相等。
Sample Input
12   5
    10     A
12 34
  123   456
  1    2
  10   2
0 0
Sample Output
12 (base 3) = 5 (base 6)
10 (base 10) = A (base 11)
12 (base 17) = 34 (base 5)
123 is not equal to 456 in any base 2..36
1 is not equal to 2 in any base 2..36
10 (base 2) = 2 (base 3)
0 (base 2) = 0 (base 2)

http://luckycat.kshs.kh.edu.tw/homework/q343.htm




A,B,C,......,Z則分別代表10,11,12,......,35 這一行還是看不懂

import java.util.Scanner; public class UVA_343 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(true){ String X=sc.next(),Y=sc.next(); int[] X_base=new int[37]; int[] Y_base=new int[37]; boolean flag=false; for(int i=2;i<37;i++){ try{ X_base[i]=Integer.parseInt(X,i); }catch(Exception e){ X_base[i]=-1; } try{ Y_base[i]=Integer.parseInt(Y,i); }catch(Exception e){ Y_base[i]=-1; } } System.out.println(Y_base[11]); int base_x=-1,base_y=-1; for(int i=2;i<37;i++){ if(X_base[i]>=0){ for(int j=2;j<37;j++){ if(X_base[i]==Y_base[j]){ flag=true; base_x=i; base_y=j; break; } } } if(flag) break; } if(flag) System.out.println(X+" (base "+base_x+")="+Y+" (base "+base_y+")"); else{ System.out.println(X+" is not equal to "+Y+" in any base 2..36"); } } } }

沒有留言:

張貼留言