题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
忘记了可以用Integer.parseInt(c,16)先转换成16进制,把0-9和a-f都包含进去,就不用分开讨论了。所以0-9和a-f是分开进行转换的,转a-f的时候又想起0-9、a-f总共也就16个字符,完全可以直接口算,然后存进HashMap里,用的时候直接查就得了,所以也懒得想a-f怎么转换了,总共6个字母就直接return算了,搞出个四不像来.....反正写出来就行
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine().trim().replace(" ",""); ArrayList<Character> evenList = new ArrayList<>(); ArrayList<Character> oddList = new ArrayList<>(); //把字符分别存入偶数列表、奇数列表 for (int i = 0; i < s.length(); ++i) { if (i % 2 == 0) { evenList.add(s.charAt(i)); } else { oddList.add(s.charAt(i)); } } Collections.sort(evenList); Collections.sort(oddList); StringBuilder sb = new StringBuilder(); //分别从偶数表、奇数表中读取字符并转换,然后拼接后输出 for (int i = 0; i < s.length(); ++i) { char c; if (i % 2 == 0) { c = evenList.get(i / 2); } else { c = oddList.get(i / 2) ; } //对字符进行转换 c = changeCharacter(c); sb.append(c); } System.out.println(sb.toString()); } public static char changeCharacter(char c) { //对0-9数字进行转换 if (c >= '0' && c <= '9') { //字符->字符串->数字->二进制字符串 int n = Integer.parseInt(String.valueOf(c)); String binary = Integer.toBinaryString(n); //这里也可以在补0后直接s.substring(binary.length())截取4位 //不过在for循环里控制长度,效果是一样的 String s = "0000" + binary; int sum = 0; //二进制字符串->颠倒->数字 for (int i = s.length()-1; i >=s.length()-4 ; --i) { int k = Integer.parseInt(String.valueOf(s.charAt(i))); sum = sum * 2 + k; } c = Integer.toHexString(sum).toUpperCase().charAt(0); return c; } //对a-f、A-F字母进行转换 if (Character.isLetter(c)) { if (c == 'A'||c == 'a') { return '5'; } else if (c == 'B'||c == 'b') { return 'D'; } else if (c == 'C'||c == 'c') { return '3'; } else if (c == 'D'||c =='d') { return 'B'; } else if (c == 'E'||c == 'e') { return '7'; } else if (c == 'F'||c == 'f') { return 'F'; } } return c; } }