题解 | #字符串合并处理#-Java
字符串合并处理
http://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
import java.util.*; public class Main{ private static char[] array={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; public static void main(String[] args){ Scanner input = new Scanner(System.in); while(input.hasNext()){ String str1 = input.next(); String str2 = input.next(); String mergeStr = str1 + str2; //长度为奇数时,偶数序列多一个 int len1 = mergeStr.length() % 2 == 0 ? mergeStr.length() / 2 : mergeStr.length() / 2 + 1; int len2 = mergeStr.length() / 2; char[] array1 = new char[len1]; char[] array2 = new char[len2]; for(int i = 0;i < mergeStr.length();i++){ if(i % 2 == 0){ array1[i / 2] = mergeStr.charAt(i); }else{ array2[i / 2] = mergeStr.charAt(i); } } Arrays.sort(array1); Arrays.sort(array2); StringBuilder builder = new StringBuilder(); for(int i = 0;i < mergeStr.length(); i++){ if(i % 2 == 0){ builder.append(bitRotate(array1[i / 2])); }else{ builder.append(bitRotate(array2[i / 2])); } } System.out.println(builder.toString()); } } //这里反转简单思路是例 0001 是从右到左2 bit下标对应n次之和,翻转就从左到右2的n次之和就可以 private static char bitRotate(char a){ int number = 0; if(a >= 'a' && a<= 'f'){ number = a - 'a' + 10; }else if(a >= 'A' && a <= 'F'){ number = a - 'A' + 10; }else if(a >= '0' && a <= '9'){ number = a - '0'; }else{ return a; } int tag = 8; int result = 0; for(int i = 0;i<4;i++){ if((number & tag) == tag){ result += Math.pow(2,i); } number = number << 1; } return array[result]; } }