题解 | #字符串合并处理# 优雅操作 + 简单位运算
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*;
public class Main {
public String merge(String s1, String s2){
String temp = s1 + s2;
char[] odd = new char[temp.length() / 2];
char[] even = new char[temp.length() - odd.length];
//5 0 1 2 3 4 0 1 2 3
for(int i = 0; i < temp.length(); i++){
if((i & 1) == 0)
even[i / 2] = temp.charAt(i);
else
odd[i / 2] = temp.charAt(i);
}
Arrays.sort(odd);
Arrays.sort(even);
char[] ans = new char[temp.length()];
for(int i = 0; i < temp.length(); i++){
char c;
if((i & 1) == 0)
c = even[i / 2];
else
c = odd[i / 2];
if(c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' || c >= '0' && c <= '9'){
int num = c - '0';
if(c >= 'a' && c <= 'f')
num = (c - 'a' + 10);
else if(c >= 'A' && c <= 'F')
num = c - 'A' + 10;
num = reverseNum(num);
if(num > 9)
c = (char) ('A' + num - 10);
else
c = (char) (num + '0');
}
ans[i] = c;
}
return new String(ans);
}
public int reverseNum(int num){
int res = 0;
for(int i = 0; i < 4; i++){
if(((1 << i) & num) != 0)
res += (1 << (3 - i));
}
return res;
}
public static void main(String[] args) {
Main main = new Main();
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
String s2 = scanner.next();
System.out.println(main.merge(s1,s2));
}
}
其实题目倒是很简单 就是操作复杂,主要以下三点:
1. 给奇偶数组赋值的时候可以通过下标运算一次循环内赋值完。
不管是数组长度是奇数还是偶数,奇数下标的个数永远是length / 2.
2. char类型与10进制表示永远和'a'还有'A'相关 注意相减关系即可。
3. 反转时不能调用系统api来反转,因为系统api会省略掉前导0. 故自己通过位运算来判定反转后的1的个数,注意只需要判断4位即可因为A -F最多存满4位
