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

字符串合并处理

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

#include <algorithm>
#include <iostream>
#include <bitset>
#include <cmath>
using namespace std;

char get_rev_char(char x) {
    string s;
    int num = 0;
    if (x >= '0' && x <= '9') {
        num = x - '0';
    }
    if (x >= 'a' && x <= 'f') {
        num = 10 + x - 'a';
    }
    if (x >= 'A' && x <= 'F') {
        num = 10 + x - 'A';
    }
    bitset<4> binary(num);
    s = binary.to_string();
    reverse(s.begin(), s.end());
    int digit = 0;
    int res = 0;
    for (int i = s.size() - 1; i >= 0; i--) {
        res += (s[i] - '0') * (1 << digit); 
        digit++;
    }
    if (res >= 0 && res <= 9) {
        return '0' + res;
    }
    if (res >= 10 && res <= 15) {
        return 'A' + res - 10;
    }
    return ' ';
}

int main() {
    string s;
    string s1, s2;
    int flag = 1;
    int size = 0;
    while (getline(cin, s)) {
        auto x = s.find(' ');
        s.erase(x, 1);
        for (int i = 0; i < s.size(); i++) {
            if (i % 2 == 0) {
                s1 += s[i];
            } else {
                s2 += s[i];
            }
        }
        sort(s1.begin(), s1.end());
        sort(s2.begin(), s2.end());
        size = s.size();
        s.clear();
        for (int i = 0; i < size; i++) {
            if (flag == 1) {
                s += s1[i / 2];
                flag = 0;
            } else if (flag == 0) {
                s += s2[(i - 1) / 2];
                flag = 1;
            }
        }
        for (int i = 0; i < s.size(); i++) {
            if((s[i]>='0'&&s[i]<='9')||(s[i]>='a'&&s[i]<='f'||(s[i>='A']&&s[i]<='F'))){
                s[i] = get_rev_char(s[i]); 
            }
        }
        cout << s << endl;
    }
}

全部评论

相关推荐

冷艳的小师弟在看机会:jd测评乱点直接被挂了,哭死~
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务