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

字符串合并处理

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

import java.util.*;

public class Main {
    public  static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        String str2 = sc.next();
        String str = str1 + str2;
        char[] arr = str.toCharArray();
        int n = arr.length;
        char[] even = new char[n / 2];
        char[] odd = n % 2 == 0 ? new char[n / 2] : new char[n / 2 + 1];
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                odd[i / 2] = arr[i];
            } else {
                even[i / 2] = arr[i];
            }
        }
        Arrays.sort(odd);
        Arrays.sort(even);
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                arr[i] = odd[i / 2];
            } else {
                arr[i] = even[i / 2];
            }
        }
        StringBuilder sb = new StringBuilder();
        for (char i : arr) {
            sb.append(transform(i));
        }
        System.out.println(sb);
    }

    public static Object transform(char ch) {
        int num = 0;
        if (ch >= '0' && ch <= '9') {
            num = ch - 48;
        } else if (ch >= 'a' && ch <= 'f') {
            num = ch - 87;
        } else if (ch >= 'A' && ch <= 'F') {
            num = ch - 55;
        }else{
            return ch;
        }

        int i = 0;
        int sum=0;
        while (num > 0) {
            int remainder = num % 2;
            num /= 2;
            if (remainder == 0) {
                i++;
                continue;
            }
            int temp = 1;
            int j = 3-i;
            while (j > 0) {
                temp *= 2;
                j--;
            }
            sum += temp;
            i++;
        }
        if (sum < 10){
            return sum;
        }
        return (char)(Character.forDigit(sum & 15, 16)-32);
    }


}
全部评论

相关推荐

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