limitaciones de recursos
Límite de tiempo: 1,0 s Límite de memoria: 512,0 MB
Descripción del problema
Dados n enteros hexadecimales positivos, genera sus números octales correspondientes.
formato de entrada
La primera línea de entrada es un entero positivo n (1<=n<=10).
En las siguientes n líneas, cada línea contiene una cadena que consta de 0 a 9 y letras mayúsculas de la A a la F, lo que indica el número entero positivo hexadecimal que se va a convertir, y la longitud de cada número hexadecimal no supera los 100.000.
formato de salida
Salida n líneas, cada línea corresponde a la entrada de entero positivo octal.
[Nota]
El número hexadecimal de entrada no tendrá un 0 inicial, como 012A.
El número octal de salida tampoco puede tener un 0 inicial
import java.util.*;
public class hexadecimalToOctal
{
public static String SixteenToEight(String str)
{
StringBuilder stringbuilder = new StringBuilder();
char[] ch = str.toCharArray();
for (char c :ch)
{
int temp;
if (c >= 'A' && c <= 'F')
{
temp = c - 'A' + 10;
} else
temp = c - '0';
// c - 'A'返回 ASCII码值
Stack<Integer> stack = new Stack<>();
// 利用栈先进后出的特点储存转换后的二进制
for (int i = 0; i < 4; i++)
{
int n = temp % 2;
temp = temp / 2;
stack.push(n);
// 每四位二进制对应一位十六进制
}
while (!stack.isEmpty())
{
stringbuilder.append(stack.pop());
}
}
String result = stringbuilder.toString();
return TwoToEight(result);
}
public static String TwoToEight(String str)
{
char[] ch = str.toCharArray();
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int n = 0; n < 3 - ch.length % 3; n++)
{
stack1.push(0);
// 每三位二进制对应一位八进制,不够补齐
}
for (char c : ch)
{
stack1.push(Integer.parseInt(String.valueOf(c)));
}
while (!stack1.isEmpty())
{
stack2.push(stack1.pop() + stack1.pop() * 2 + stack1.pop() * 4);
}
while(!stack2.isEmpty())
{
sb.append(stack2.pop());
}
char[] chars = sb.toString().toCharArray();
int count = 0;
// 对前导 0计数
for(char c : chars)
{
if(c == '0')
{
count++;
}
else
break;
}
char[] result = new char[chars.length-count];
if (chars.length - count >= 0)
System.arraycopy(chars, count, result, 0, chars.length - count);
// 去除前导 0
return String.valueOf(result);
}
public static void main(String[] args)
{
Scanner sr = new Scanner(System.in);
int n = sr.nextInt();
sr.nextLine();
String[] A = new String[n];
for(int i = 0;i < n;i++)
{
String temp = sr.nextLine();
A[i] = temp;
}
sr.close();
String[] result = new String[n];
for(int i = 0;i < n;i++)
{
result[i] = SixteenToEight(A[i]);
System.out.println(result[i]);
}
}
}