题解 | #字符串合并处理#

字符串合并处理

https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f

华为很多这种繁琐的转换题,根据题意转就行了
import java.io.IOException;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        //Eqr v9oEb12U2ur4xu7rd931G1f50qDo
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next() + scanner.next();
        char[] chars = str.toCharArray();
        int half = chars.length >> 1;
        char[] oddChars = new char[half];
        char[] evenChars = new char[(chars.length & 1) == 0 ? half : half + 1];

        for (int i = 0, j = 0, k = 0; i < chars.length; i++) {
            if ((i & 1) == 0) {
                evenChars[j++] = chars[i];
            } else {
                oddChars[k++] = chars[i];
            }
        }

        Arrays.sort(oddChars);
        Arrays.sort(evenChars);

        char[] newChars = new char[chars.length];
        for (int i = 0, j = 0, k = 0; i < chars.length; i++) {
            char c = (i & 1) == 0 ? evenChars[j++] : oddChars[k++];

            String binaryStr = null;
            if (Character.isDigit(c)) {
                binaryStr = Integer.toBinaryString((c - '0'));
            } else if (c >= 'a' && c <= 'f') {
                binaryStr = Integer.toBinaryString((c - 'a') + 10);
            } else if (c >= 'A' && c <= 'F') {
                binaryStr = Integer.toBinaryString((c - 'A') + 10);
            }

            if (binaryStr != null) {
                char[] reversedChars = new char[4];
                for (int l = 0; l < reversedChars.length; l++) {
                    int index = binaryStr.length() - l - 1;
                    if (index >= 0) {
                        reversedChars[l] = binaryStr.charAt(index);
                    } else {
                        reversedChars[l] = '0';
                    }
                }
                int num = Integer.parseInt(new String(reversedChars), 2);
                if (num >= 10) {
                    c = (char) ('A' + num - 10);
                } else {
                    c = (char) ('0' + num);
                }
            }

            newChars[i] = c;
        }

        System.out.println(new String(newChars));
    }

}


全部评论

相关推荐

05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 17:37
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务