@java Blue Bridge Cup Group B Exercise Basics (30) question 12: Hex turn octal
Problem Description
Given a positive integer n hexadecimal, octal output thereof corresponds.
Input format
input acts a first positive integer n (1 <= n <= 10).
Next n lines, each line a from 0 to 9, the uppercase A string consisting of F, converted to hexadecimal represents a positive integer, each hexadecimal number length does not exceed 100,000.
Output format
output n lines, each act input corresponding octal positive integer.
[Note]
enter the hexadecimal number does not have leading 0, such as 012A.
Octal number also can not have a leading zero.
Sample input
2
39
123ABC
Sample Output
71 is
4,435,274
[Note]
first convert a hexadecimal number to a decimal number, and then converted by a binary number to octal.
Code:
(This question is I was not able to make the right answer, but I found a big brother to write online, after the submission of the evaluation results are out here for everyone to share, you can also see the original big brother oh ~ !)
import java.util.Scanner;
import java.util.Stack;
public class HexadecimalConversionToOctal{
static String convert16To2(char c) {
int temp = c >= ‘A’ ? c - ‘A’ + 10 : c - ‘0’;
int[] a = new int[4];
int i = 0;
for (; i < a.length; i++) {
a[i] = temp % 2;
temp /= 2;
}
i–;
StringBuffer sb = new StringBuffer();
for (; i >= 0; i–) {
sb.append(a[i]);
}
return sb.toString();
}
static String convert2To8(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
result += Math.pow(2, str.length() - 1 - i) * (str.charAt(i) - '0');
}
return result + "";
}
static void convert16To8(String n) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n.length(); i++) {
sb.append(convert16To2(n.charAt(i)));// 把16进制数的每一位转换成四位2进制数字
}
Stack<String> stack = new Stack<>();
for (int i = sb.length(); i >= 0; i -= 3) {
int start = i - 3 >= 0 ? i - 3 : 0;
String temp = sb.substring(start, i);
stack.add(convert2To8(temp));// 从后向前每三位2进制数字转换成一位8进制数字,存储在栈中。
}
while (stack.peek().equals("0")) {
stack.pop();// 删除前面的多余的0
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String[] strings = new String[n];
for (int i = 0; i < n; i++) {
strings[i] = sc.next();
}
for (String string : strings) {
if (string.equals("0")) {
System.out.println(0);
} else {
convert16To8(string);
}
}
}
}