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

字符串合并处理

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

#include <iostream>
#include <string>
#include <vector>
#include <math.h>

using namespace std;

void transform(char &c);
int reverseDec(int &num);

int main() {
    // 输入字符串
    string str1,str2;
    cin >> str1 >> str2;
    // 合并字符串
    string str = str1 + str2;
    // 字符串排序
    for (int i = 1; i < str.size() / 2 + 1; i++) {
        for (int j = 0; j < str.size() - i - 1; j += 2) {
            if (str[j] - str[j + 2] > 0) {
                swap(str[j], str[j + 2]);
            }
        }
        for (int k = 1; k < str.size() - i - 1; k += 2) {
            if (str[k] - str[k + 2] > 0) {
                swap(str[k], str[k + 2]);
            }
        }
    }
    // 字符转换
    for (auto &c : str) {
        if ((c - '0' >= 0 && c - '9' <= 0) || 
            (c - 'A' >= 0 && c - 'F' <= 0) || 
            (c - 'a' >= 0 && c - 'f' <= 0)) {
            transform(c);
        }
    }
    cout << str << endl;
    return 0;
}

void transform(char &c) {
    int numDec;
    if (c - '0' >= 0 && c - '9' <= 0) {
        numDec = c - '0';
    }
    else if (c - 'A' >= 0 && c - 'F' <= 0) {
        numDec = 10 + c - 'A';
    }
    else if (c - 'a' >= 0 && c - 'f' <= 0) {
        numDec = 10 + c - 'a';
    }
    numDec = reverseDec(numDec);
    if (numDec <= 9) {
        c = '0' + numDec;
    }
    else {
        c = numDec - 10 + 'A';
    }
}

int reverseDec(int &num) {
    vector<int> numBin;
    while (num > 1) {
        numBin.push_back(num % 2);
        num /= 2;
    }
    numBin.push_back(num);
    while (numBin.size() < 4) {
        numBin.push_back(0);
    }
    int retVal = 0;
    for (int i = 0; i < numBin.size(); i++) {
        retVal += numBin[numBin.size() - 1 - i] * pow(2, i);
    }
    return retVal;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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