题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case String a = in.nextLine().replaceAll(" ", ""); // System.out.println(getMix(a)); // System.out.println((int)'0'); String str = getMix(a); // System.out.println(str); char[] charArr = str.toCharArray(); int n = charArr.length; for (int i = 0; i < n; i++) { charArr[i] = changeChar(charArr[i]); } String str2 = new String(charArr); System.out.println(str2); } } public static char changeChar(char input) { String tempStr = null; if (input >= '0' && input <= '9') { tempStr = Integer.toBinaryString(input - '0'); } else if (input >= 'A' && input <= 'F') { tempStr = Integer.toBinaryString(input - '7'); } else if (input >= 'a' && input <= 'f') { tempStr = Integer.toBinaryString(input - 'W'); } else { return input; } // System.out.println(tempStr); while (tempStr.length() < 4) { tempStr = "0" + tempStr; } char[] tempCharArr = tempStr.toCharArray(); //反向遍历 int sum = 0; for (int i = 3; i > -1; i--) { sum += (tempCharArr[i] - '0') * Math.pow(2, i); } if (sum >= 0 && sum <= 9) { return (char)(sum + 48); } else { return (char)(sum + 55); } } public static String getMix(String input1) { char[] input2 = input1.toCharArray(); char[] ouShu = new char[input2.length / 2 + input2.length % 2]; char[] jiShu = new char[input2.length / 2]; for (int i = 0; i < input2.length; i++) { if (i % 2 == 0) { ouShu[i / 2] = input2[i]; } else { jiShu[(i - 1) / 2] = input2[i]; } } Arrays.sort(ouShu); Arrays.sort(jiShu); for (int i = 0; i < input2.length; i++) { if (i % 2 == 0) { input2[i] = ouShu[i / 2]; } else { input2[i] = jiShu[(i - 1) / 2]; } } return (new String(input2)); } }