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

字符串合并处理

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

对char[]使用冒泡排序

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str1 = in.next(), str2 = in.next();
            char[] chars = str1.concat(str2).toCharArray();
            for (int i = 0; i < chars.length; i+=2) {
                for (int j = 0; j + 2 < chars.length - i; j+=2) {
                    if (chars[j] > chars[j + 2]) {
                        char temp = chars[j];
                        chars[j] = chars[j + 2];
                        chars[j + 2] = temp;
                    }
                }
            }
            for (int i = 1; i < chars.length; i+=2) {
                for (int j = 1; j + 2 <= chars.length - i; j+=2) {
                    if (chars[j] > chars[j + 2]) {
                        char temp = chars[j];
                        chars[j] = chars[j + 2];
                        chars[j + 2] = temp;
                    }
                }
            }
            // System.out.println(chars);
            for (int i = 0; i < chars.length; i++) {
                String s = String.valueOf(chars[i]);
                if (s.matches("[0-9A-Fa-f]")) {
                    StringBuilder bin = new StringBuilder(Integer.toBinaryString(Integer.parseInt(s, 16)));
                    while (bin.length() < 4) {
                        bin.insert(0, "0");
                    }
                    chars[i] = Integer.toHexString(Integer.parseInt(bin.reverse().toString(), 2)).toUpperCase().charAt(0);
                }

            }
            System.out.println(chars);
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务