蓝桥杯错题记录 - 十六进制转八进制


import java.util.Scanner;

public class Main {
	private static final String[] strs={"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[] strs = new String[n];
		for (int i = 0; i < n; i++) {
			strs[i] = input.next();
		}
		input.close();
		for (int i = 0; i < n; i++) {
			StringBuilder result = new StringBuilder();		
			result = hexTobin(strs[i]);
			binTooct(result);	
		}
	}
	public static void binTooct(StringBuilder str) {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < str.length()-2; i+=3) {
			result.append(switchsO(str.substring(i, i+3)));
		}
		if ("0".equals(result.substring(0,1))) {
			System.out.println(result.substring(1));
			return;
		}
		System.out.println(result);
	}
	public static StringBuilder hexTobin(String str) {
		StringBuilder result = new StringBuilder();
		for (int i = 0; i < str.length(); i++) {
			result.append(switchH(str.charAt(i)));
		}
		int length = result.length();
		if (length % 3 != 0 ) {
			int n = length%3;
			switch (n) {
			case 1:
				result.insert(0,"00");
				break;
			case 2:
				result.insert(0,"0");
				break;
			}
		}
		return result;
	}
	public static String switchH(char c) {
		switch (c) {
		case '0':
			return strs[0];
		case '1':
			return strs[1];
		case '2':
			return strs[2];
		case '3':
			return strs[3];
		case '4':
			return strs[4];
		case '5':
			return strs[5];
		case '6':
			return strs[6];
		case '7':
			return strs[7];
		case '8':
			return strs[8];
		case '9':
			return strs[9];
		case 'A':
			return strs[10];
		case 'B':
			return strs[11];
		case 'C':
			return strs[12];
		case 'D':
			return strs[13];
		case 'E':
			return strs[14];
		case 'F':
			return strs[15];
		}
		return "";
	}
	public static String switchsO(String s) {
		switch (s) {
		case "000":
			return "0";
		case "001":
			return "1";
		case "010":
			return "2";
		case "011":
			return "3";
		case "100":
			return "4";
		case "101":
			return "5";
		case "110":
			return "6";
		case "111":
			return "7";
		}
		return "";
	}
}

你可能感兴趣的:(日常学习)