BASIC-12-十六进制转八进制
最后更新于:2022-04-01 09:41:23
问题描述
给定n个十六进制正整数,输出它们对应的八进制数。
输入格式
输入的第一行为一个正整数n (1<=n<=10)。
接下来n行,每行一个由0~9、大写字母A~F组成的字符串,表示要转换的十六进制正整数,每个十六进制数长度不超过100000。
输出格式
输出n行,每行为输入对应的八进制正整数。
【注意】
输入的十六进制数不会有前导0,比如012A。
输出的八进制数也不能有前导0。
样例输入
2
39
123ABC
样例输出
71
4435274
【提示】
先将十六进制数转换成二进制数,再由二进制数转换成八进制。
难点就是数值太大了,10w个F啊, 思路就是换成二进制再换成八进制,用java大数类一直超时,所以不能用大数方法
### 先来超时的方法
~~~
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] arr = new String[n];
for (int i = 0; i < n; i++) {
String temp = input.next();
BigInteger num = new BigInteger(temp,16);
arr[i] = num.toString(8).toUpperCase();
}
for (String string : arr) {
System.out.println(string);
}
}
}
~~~
### 下面是正确的方法
~~~
package com.day7;
import java.util.Scanner;
public class Main {
//定义16进制需要的二进制码
static String[] hex = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] arrs = new String[n];
for (int i = 0; i < n; i++) {
arrs[i] = input.next();
}
for (int i = 0; i < arrs.length; i++) {
translateToOct(translateToBin(arrs[i]));
}
}
//把得到的二进制串转换成八进制
private static void translateToOct(StringBuilder builder){
StringBuilder builder2 = new StringBuilder();
for (int i = 0; i < builder.length()-1; i = i+3) {
switch (builder.substring(i, i+3)) {
case "000":
builder2.append("0");
break;
case "001":
builder2.append("1");
break;
case "010":
builder2.append("2");
break;
case "011":
builder2.append("3");
break;
case "100":
builder2.append("4");
break;
case "101":
builder2.append("5");
break;
case "110":
builder2.append("6");
break;
case "111":
builder2.append("7");
break;
}
}
if (builder2.charAt(0) == '0') {
builder2.deleteCharAt(0);
}
System.out.println(builder2.toString());
}
//把输入的字符串变成二进制串
private static StringBuilder translateToBin(String str){
StringBuilder builder = new StringBuilder();
//转换后补0凑成3的倍数
if ((str.length()*4)%3 != 0) {
if ((str.length()*4)%3 == 1) {
builder.append("00");
}else {
builder.append("0");
}
}
//接下来开始转换
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case '0':
builder.append(hex[0]);
break;
case '1':
builder.append(hex[1]);
break;
case '2':
builder.append(hex[2]);
break;
case '3':
builder.append(hex[3]);
break;
case '4':
builder.append(hex[4]);
break;
case '5':
builder.append(hex[5]);
break;
case '6':
builder.append(hex[6]);
break;
case '7':
builder.append(hex[7]);
break;
case '8':
builder.append(hex[8]);
break;
case '9':
builder.append(hex[9]);
break;
case 'A':
builder.append(hex[10]);
break;
case 'B':
builder.append(hex[11]);
break;
case 'C':
builder.append(hex[12]);
break;
case 'D':
builder.append(hex[13]);
break;
case 'E':
builder.append(hex[14]);
break;
case 'F':
builder.append(hex[15]);
break;
}
}
return builder;
}
}
~~~