蓝桥杯- 基础练习:十六进制转八进制
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); String[] strings = new String[size]; for (int i = 0; i < strings.length; i++) { strings[i] = scanner.next(); } for (int i = 0; i < strings.length; i++) { toBinaryString(strings[i]); } } private static void toBinaryString(String string) { String str = string.toUpperCase(); char[] chars = str.toCharArray(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < chars.length; i++) { switch (chars[i]) { case '0': buffer.append("0000"); break; case '1': buffer.append("0001"); break; case '2': buffer.append("0010"); break; case '3': buffer.append("0011"); break; case '4': buffer.append("0100"); break; case '5': buffer.append("0101"); break; case '6': buffer.append("0110"); break; case '7': buffer.append("0111"); break; case '8': buffer.append("1000"); break; case '9': buffer.append("1001"); break; case 'A': buffer.append("1010"); break; case 'B': buffer.append("1011"); break; case 'C': buffer.append("1100"); break; case 'D': buffer.append("1101"); break; case 'E': buffer.append("1110"); break; case 'F': buffer.append("1111"); break; } } toOctalString(buffer); } private static void toOctalString(StringBuffer buffer) { int len = buffer.length(); if(len%3==0) { if(buffer.substring(0,3).equals("000")) { buffer.delete(0, 3); } } if(len%3==1) { if(buffer.substring(0,1).equals("0")) { buffer.delete(0, 1); }else { buffer.insert(0, "00"); } } if(len%3==2) { if(buffer.substring(0,2).equals("00")) { buffer.delete(0, 2); }else { buffer.insert(0, "0"); } } StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < buffer.length()/3; i++) { String substring = buffer.substring(i*3,i*3+3); switch (substring) { case "000": stringBuffer.append("0"); break; case "001": stringBuffer.append("1"); break; case "010": stringBuffer.append("2"); break; case "011": stringBuffer.append("3"); break; case "100": stringBuffer.append("4"); break; case "101": stringBuffer.append("5"); break; case "110": stringBuffer.append("6"); break; case "111": stringBuffer.append("7"); break; } } System.out.println(stringBuffer.toString()); } }