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

字符串合并处理

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

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.next();
            String b = in.next();
            convert(a + b);
        }
    }

//dec fab
    private static void convert(String str) {
        char[] arr = str.toCharArray();
        String a = "";
        String b = "";
        int i = 0;
        for (char c : arr) {
            if (i%2 == 0) {
                a += c;
            } else {
                b += c;
            }
            i++;
        }

        String r = "";
        Iterator<Character> ita = sort(a);
        Iterator<Character> itb = sort(b);
        while (ita.hasNext()) {
            r += ita.next();
            if (itb.hasNext())
                r += itb.next();
        }

        String rr = "";
        for (int k = 0; k < r.length(); k++) {
            char kchar = r.charAt(k);
            if ("0123456789ABCDEFabcdef".indexOf(kchar) >= 0) {
                rr += two(kchar).toUpperCase();
            } else {
                rr += kchar;
            }
        }
        System.out.println(rr);
    }

    private static Iterator<Character> sort(String a) {
        List list = Arrays.asList(a.split(""));
        Collections.sort(list);
        return list.iterator();
    }

    private static String two(char a) {
        String numstr = a + "";
        String r = Integer.toBinaryString(Integer.parseInt(numstr, 16));//转二进制
        StringBuffer s = new StringBuffer(String.format("%4s", r).replace(' ', '0'));
        s = s.reverse();
        int ten = Integer.parseInt(s.toString(), 2);//10
        return Integer.toHexString(ten);
    }
}

全部评论

相关推荐

程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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