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

字符串合并处理

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

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            //step 1
            String s1 = sc.next();
            String s2 = sc.next();
            String s3 = s1+s2;
            char[] chars = s3.toCharArray();
            //Arrays.sort()可以用于排序字符数组,btw
            //但是因为并不清楚数组的长度,使用char[]来存储奇数偶数下标的字符不方便
            //故而考虑使用列表
            List<Character> listOdd = new ArrayList<>();
            List<Character> listEven = new ArrayList<>();
            for(int i=0;i<chars.length;i++){
                if(i%2==0){
                    listEven.add(chars[i]);
                }
                else{
                    listOdd.add(chars[i]);
                }
            }
            //step 2
            Collections.sort(listEven);
            Collections.sort(listOdd);
            for(int i=0;i<chars.length;i++){
                if(i%2==0){
                    chars[i]=listEven.get(i/2);//chars就重复利用,反正大小一样
                }
                else{
                    chars[i]=listOdd.get((i-1)/2);
                }
            }
            //step 3
            for(int i=0;i<chars.length;i++){
                char c = chars[i];
                char ans = c;
            //数字就先将其字符c转成string,再转成int,才可以得到二进制string,如‘7’-“7”-7-“0111”
                if(Character.isDigit(chars[i])){
           String binNum = Integer.toBinaryString(Integer.parseInt(Character.toString(chars[i])));
                    ans = trans(binNum);
                }
            //不是数字反而方便,利用ascii码,但是要记得先变成小写,同一计算
            //之后过程类似上面
                else if((c>='a'&&c<='f')||(c>='A'&&c<='F')){
                    char t = Character.toLowerCase(c);
                    String binNum = Integer.toBinaryString(t-'a'+10);
                    ans = trans(binNum);
                }
                System.out.print(ans);
            }

        }
    }
    
    //将二进制的string反转再输出对应的字符
    public static Character trans(String s){
        StringBuilder sb = new StringBuilder(s);
        //趁没开始反转,补个零先,使string的长度达到4
        while(sb.length()<4){
            sb = new StringBuilder("0"+sb.toString());
        }
        sb.reverse();
        int ans = Integer.parseInt(sb.toString(),2);
        String s2 = Integer.toString(ans);
        if(ans<10){
            return (char)('0'+ans);//小于10直接转char,切记要'0'+,因为char强转是
                           //根据ascii来的,此时括号里的数是一个ascii码
        } 
        else{
            return Character.toUpperCase((char)('a'+ans-10));//大于10类似上面
                                              //题目要求全部大写,就再加一个uppercase
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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