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


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 "";
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值