题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
char to2(int m) {
char ch;
int i = 0, n = 0;
//利用数组实现幂的标记
int a[4] = {0};
if (m == 1)
a[0] = 1;
else if (m != 0) {
while (pow(2, i) < m) {
i++;
if (pow(2, i) > m) {
m -= pow(2, i - 1);
a[i - 1] = 1;
i = 0;
}
}
//只有当pow(2, i) == m时才会跳出循环
a[i] = 1;
}
//反向累计,计算十进制的值
for (i = 0; i < 4; ++i) {
n += a[i] * pow(2, 3 - i);
}
//换算成16进制
if (n >= 0 && n <= 9)
ch = char( n + '0');
else
ch = char(n - 10 + 'A');
return ch;
}
char trans(char c) {
int num;
//将16进制转为10进制
if (c >= '0' && c <= '9')
num = stoi(to_string(c));
else if (c >= 'A' && c <= 'F')
num = 10 + c - 'A';
else if (c >= 'a' && c <= 'f')
num = 10 + c - 'a';
else
return c;
//完成转变
return to2(num);
}
int main() {
string str1, str2, str_even, str_odd, str;
//输入两个字符串
cin >> str1 >> str2;
str1 += str2;
//分成奇偶字符串
for (int i = 0; i < str1.length(); ++i) {
if (i % 2 == 0)
str_even += str1[i];
else
str_odd += str1[i];
}
//字符串按大小排序
sort(str_even.begin(), str_even.end());
sort(str_odd.begin(), str_odd.end());
int i = 0;
//按照奇偶排序,拼成字符串
while (i < str1.length()) {
if (i % 2 == 0) {
str += str_even[i / 2];
} else {
str += str_odd[(i - 1) / 2];
}
i++;
}
string str_new;
for (auto s : str) {
str_new += trans(s);
}
cout << str_new;
//cout<< to2(3);
}
// 64 位输出请用 printf("%lld")