题意
输入 n (行)
输入 n 个 16进制字符串 && 1 <= hex_chs.lehgth <= 10000 -> 16^(10000 - 1) -近似> 16^10000 -> 2^40000 >> 2^31(int) or 2^63(long) -> 中间数不能用整型->char[ ]
分别每行输出 1 个 8进制字符串
(结合16进制 = 4 bits , 8进制 = 3 bits -> 中间数取binary_chs)
代码
import java.awt.AlphaComposite;
import java.util.Scanner;
public class Main {
static char[] HexAlphabet = {'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E','F'
};
static String[] HexBin = { "0000","0001","0010","0011",
"0100","0101","0110","0111",
"1000","1001","1010","1011",
"1100","1101","1110","1111",
};
static char[][] OctBin = { {'0','0','0'},{'0','0','1'},{'0','1','0'},{'0','1','1'},
{'1','0','0'},{'1','0','1'},{'1','1','0'},{'1','1','1'},
};
public static void main(String[] args) {
Scanner keyin = new Scanner(System.in);
int n = keyin.nextInt();
while (n-- > 0) {
String hex_str = keyin.next();
char[] hex_chs = hex_str.toCharArray();
char[] bin_chs = hexChsToBinaryChs(hex_chs);
char[] oct_chs = binChsToOctalChs(bin_chs);
System.out.println(String.valueOf(oct_chs));
}
}
public static int chsSearch(char[] target){
for (int i = 0; i < OctBin.length; i++) {
int j;
for (j = 0; j < target.length; j++) {
if( OctBin[i][j] != target[j] )
break;
}
if(j == target.length)
return i;
}
return -1;
}
public static char[] binChsToOctalChs(char[] bin_chs){
if( bin_chs.length % 3 >= 1){
bin_chs = ("0"+String.valueOf(bin_chs)).toCharArray();
if( bin_chs.length % 3 == 2){
bin_chs = ("0"+String.valueOf(bin_chs)).toCharArray();
}
}
char[] oct_chs = new char[bin_chs.length/3];
for (int i = bin_chs.length - 3; i >= 0 ; i -= 3) {
char[] oct_section = { bin_chs[i],bin_chs[i+1],bin_chs[i+2] };
int sub_oct_digit = chsSearch(oct_section);
oct_chs[i/3] = HexAlphabet[sub_oct_digit];
}
int cnt_head_zero = 0;
while(oct_chs[cnt_head_zero] == '0'){
cnt_head_zero++;
}
char[] erase_head_zero_oct_chs = new char[ oct_chs.length - cnt_head_zero];
for (int i = 0; i < erase_head_zero_oct_chs.length; i++) {
erase_head_zero_oct_chs[i] = oct_chs[i + cnt_head_zero];
}
return erase_head_zero_oct_chs;
}
public static char[] hexChsToBinaryChs(char[] hex_chs){
char[] bin_chs = new char[hex_chs.length*4];
for (int i = bin_chs.length - 4; i >= 0; i -= 4) {
int sub_hex = binSearch(HexAlphabet, hex_chs[i/4]);
System.arraycopy(HexBin[sub_hex].toCharArray(), 0,bin_chs, i , 4);
}
return bin_chs;
}
public static int binSearch(char[] src,char target){
int low = 0,high = src.length - 1,mid = 0;
do {
mid = (low + high)/2;
if(target == src[mid])
return mid;
else if(target > src[mid])
low = mid + 1;
else
high = mid - 1;
} while (low <= high);
return -1;
}
}
Summary
【两转两Search后去Zero】
i)两Search两转 -> binSearch
hex_chs + 构造HexAlphabet对照表( HexAlphabet和OctalAlphabet部分可以通用) +HexBin -> 用于 hexChsToBinaryChs
bin_chs + HexAlphabet + HexBin -> 用于 binChsToOctalChs
ii) 去Zero
在binChsToOctalCh中,将bin_chs -> oct_chs 后
iii)输出 ->sysout { String.valueOf(octal_chs) }