题解 | #字符串合并处理#
字符串合并处理
http://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.next();
// 第一步:字符串合并
str = str + sc.next();
// 第二步:字符串奇偶排序
int length = str.length();
List<Character> even = new ArrayList<>();
List<Character> odd = new ArrayList<>();
for (int i = 0; i < length; i++) {
if (i % 2 == 0) {
even.add(str.charAt(i));
} else {
odd.add(str.charAt(i));
}
}
Collections.sort(even);
Collections.sort(odd);
// 重新拼接
StringBuilder sb = new StringBuilder();
for (int i = 0; i < even.size(); i++) {
sb.append(even.get(i));
if (i < odd.size()) {
sb.append(odd.get(i));
}
}
String sort = sb.toString();
// 第三步:字符转换
for (int i = 0; i < length; i++) {
char c = sort.charAt(i);
int decimal;
if (Character.isDigit(c)) {
decimal = c - '0';
} else if (Character.isLetter(c) && (Character.toUpperCase(c) - 'F' <= 0)) {
decimal = Character.toUpperCase(c) - 'A' + 10;
} else {
System.out.print(c);
continue;
}
String binaryStr = Integer.toBinaryString(decimal);
int initLength = binaryStr.length();
if (binaryStr.length() < 4) {
for (int j = 0; j < 4 - initLength; j++) {
binaryStr = 0 + binaryStr;
}
}
String revertBinary = new StringBuilder(binaryStr).reverse().toString();
String hexStr = Integer.toHexString(Integer.valueOf(revertBinary, 2)).toUpperCase(Locale.ROOT);
System.out.print(hexStr);
}
System.out.println();
}
sc.close();
}
}