Q389: Basically Speaking
有一家製造計算機的公司請你幫忙設計新型的計算機。這台計算機必須可以做不同數字系統的轉換(例如:將一個2進位的數字轉換成10進位的數字)。這台計算機還必須有下列的特性:- 有 7-digit 的顯示
- 除了有 0 ~ 9 的按鈕之外,還有 A ~ F 的按鈕
- 支援 2 進位到 16 進位
Input
輸入含有多組測試資料。每組測試資料一列,含有 3 個數字。第一個數字為你所要轉換的數字。第二個數字為要轉換的數字為多少進位。第三個數字為要將這個數字轉成多少進位的數。在這3個數前後可能有一或多個空白字元存在。
以Sample Input 第一組測試資料為例:將 1111000 從 2 進位 轉換成 10 進位。
Output
對每組測試資料輸出一列 ,輸出轉換後出現在計算機顯示器上的數字。這些數字長度為 7,靠右對齊。如果這個數字太大無法以計算機顯示器顯示,則輸出 "ERROR"。輸出格式請參考 Sample Output。Sample Input | Sample Output |
1111000 2 10 1111000 2 16 2102101 3 10 2102101 3 15 12312 4 2 1A 15 2 1234567 10 16 ABCD 16 15 0 10 2 000234 10 10 F00000 16 10 | 120 78 1765 7CA ERROR 11001 12D687 D071 0 234 ERROR |
import java.util.Scanner;
public class UVA_389 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(true){
String sb=sc.nextLine(),s_n=sc.nextLine(),s_m=sc.nextLine();
String s="",a="",b=""; //沒是幾進位的數字也要在那邊輸入空白 有夠不爽的
for(int i=0;i<sb.length();i++)
if(sb.charAt(i)!=' ')
s+=String.valueOf(sb.charAt(i));
for(int i=0;i<s_n.length();i++)
if(s_n.charAt(i)!=' ')
a+=String.valueOf(s_n.charAt(i));
for(int i=0;i<s_m.length();i++)
if(s_m.charAt(i)!=' ')
b+=String.valueOf(s_m.charAt(i));
int n=Integer.parseInt(a),m=Integer.parseInt(b);
int ans=Integer.parseInt(s,n);
char[] bef=new char[8];
int c=0;
while(ans>0 && c<7){
bef[c++]=change(ans%m);
ans/=m;
}
if(c>=7){
System.out.println(" ERROR");
}else{
for(int i=7-c;i>1;i--)
System.out.print(" ");
for(int i=c;i>=0;i--)
System.out.print(bef[i]);
System.out.println();
}
}
}
private static char change(int a){
switch(a){
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
case 10:
return 'A';
case 11:
return 'B';
case 12:
return 'C';
case 13:
return 'D';
case 14:
return 'E';
case 15:
return 'F';
}
return 0;
}
}
沒有留言:
張貼留言