java的进制转换在Integer中都有提供相应的方法,当然自己写也不难。
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { char[] str1 = in.next().toCharArray(); char[] str2 = in.next().toCharArray(); //合并 StringBuilder res = new StringBuilder(); res.append(str1); res.append(str2); //奇偶分类 StringBuilder even = new StringBuilder(); StringBuilder odd = new StringBuilder(); for(int i = 0; i < res.length(); i++){ if(i%2 == 0) even.append(res.charAt(i)); else odd.append(res.charAt(i)); } char[] evenC = even.toString().toCharArray(); char[] oddC = odd.toString().toCharArray(); Arrays.sort(evenC); Arrays.sort(oddC); //再次合并,并非直接拼接,而是按原先的奇偶插回 int oddIndex = 0; int evenIndex = 0; StringBuilder sorted = new StringBuilder(); for(int j = 0; j < res.length(); j++){ if(j%2 == 0){ sorted.append(evenC[evenIndex]); evenIndex++; } else{ sorted.append(oddC[oddIndex]); oddIndex++; } } //转换 String dict = "0123456789abcdefABCDEF";//只是为了写起来方便 char[] sortedChar = sorted.toString().toCharArray(); for(int m = 0; m < sortedChar.length; m++){ //如果是0-9,a-f,A-F if(dict.contains(String.valueOf(sortedChar[m]))){ //转换为十进制 int decimal = Integer.parseInt(String.valueOf(sortedChar[m]),16); //转换为二进制,加leading zeros String binary = Integer.toString(decimal,2); binary = String.format("%04d", Integer.valueOf(binary)); //翻转 String reverseBinary = new StringBuilder(binary).reverse().toString(); //转换回16进制,如果是小写字符,变大写 //实际上这里无需判断是否是别的字符,因为四位二进制最大也就是1111,对应f,所以直接转换成大写 decimal = Integer.parseInt(reverseBinary,2); String hex = Integer.toString(decimal,16).toUpperCase(); sortedChar[m] = hex.charAt(0); } } System.out.println(sortedChar); } } }