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

字符串合并处理

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

#include <stdio.h>

int getNum(char ch)
{
    if(ch >= '0' && ch <= '9')
        return ch -'0';
    else if(ch >= 'a' && ch <= 'f')
        return ch - 'a' + 10;
    else if(ch >= 'A' && ch <= 'F')
        return ch - 'A' + 10;
    else
        return ch;
    return 0;
}

int swapNum(int num)
{
    int ret = 0x00;
    ret = ((num >> 3 & 0x01) << 0) |
    ((num >> 2 & 0x01) << 1) |
    ((num >> 1 & 0x01) << 2) |
    ((num >> 0 & 0x01) << 3) ; 
    return ret;
}

char getChangeChar(char ch)
{
    char str[4];
    char ret = 0;
    if((ch >= '0' && ch <= '9')||
        (ch >= 'a' && ch <= 'f')||
        (ch >= 'A' && ch <= 'F'))
        {
            sprintf(str,"%x",swapNum(getNum(ch)));
            ret = str[0];
            if(ret >= 'a' && ret <= 'f')
                ret = ret - 'a' + 'A';
            return ret;
        }
        else {
        return ch;
        }
}

int main() {
    char str[200] = {0};
    int len = 0;
    char ch = 0;
    while('\n' != (ch = getchar()))
    {
        if(' ' != ch){
            str[len++] = ch;
        }
    }
    //printf("%s ==",str);
    //order 0
    char temp = 0;
    for(int i = 0; i < len; i+=2)
    {
        for(int j = i; j < len; j+=2)
        {
            if(str[i] > str[j]){
                temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
    //printf("%s |",str);
    //order 1
    for(int i = 1; i < len; i+=2)
    {
        for(int j = i; j < len; j+=2)
        {
            if(str[i] > str[j]){
                temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }

    //printf("%s |",str);
    for(int i = 0; i < len; i++)
    {
        printf("%c",getChangeChar(str[i]));
    }

    return 0;
 }

全部评论
关键点:二进制反转用swapNum, 数字转16进制字符用sprintf
点赞 回复 分享
发布于 03-09 21:26 广东

相关推荐

10-16 09:58
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
过往烟沉:我说什么来着,java就业面就是广!
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务