题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
- 字符串合并,直接string类型相加即可
- 排序,和很多人思路一样,利用multiset容器的有序性的,装进去在取出来
- 二进制倒转,没想到用移位运算解决(这也是个好思路),就把字符串每个字符拆分,利用8421法手动转换为二进制存放在int[4]数组,然后倒序,在运算变为10进制,在转换为16进制的字符
#include<iostream> #include<set> using namespace std; struct rule{ bool operator()(char a,char b){ return (a<b); } }; string convertnum(string str) { int temp; int num_10; for(int i=0 ; i<str.length();i++){ if(str[i]>='0'&&str[i]<='9'){ num_10 = str[i] - '0'; }else if(str[i]>='a'&&str[i]<='f'){ num_10 = str[i] - 'a' + 10; }else if(str[i]>='A'&&str[i]<='F'){ num_10 = str[i] - 'A' + 10; }else{ continue; } int num_2[4]; num_2[3] = num_10/8; num_10 = num_10 % 8; num_2[2] = num_10/4; num_10 = num_10 % 4; num_2[1] = num_10/2; num_10 = num_10 % 2; num_2[0] = num_10/1; num_10 = num_2[3] + num_2[2]*2 + num_2[1]*4 + num_2[0]*8; if(num_10>=0&&num_10<=9){ str[i] = num_10 + '0'; }else if(num_10>9&&num_10<16){ str[i] = num_10 + 'A' - 10; }else{ cout<<"num_10 error! : "<<num_10 <<endl; } } return str; } int main() { string str1,str2; multiset<char,rule>strset0; multiset<char,rule>strset1; string str; cin>>str1>>str2; str = str1 + str2; for(int i=0 ;i<str.length();i=i+2){ strset0.insert(str[i]); } for(int i=1 ;i<str.length();i=i+2){ strset1.insert(str[i]); } int n = 0; auto it0 = strset0.begin(); auto it1 = strset1.begin(); for(;it0!=strset0.end()&&it1!=strset1.end();it0++,it1++){ str[n] = *it0; n++; str[n] = *it1; n++; } if(it0!=strset0.end()){ str[n] = *it0; }else if(it1!=strset1.end()){ str[n] = *it1; } str = convertnum(str); cout<<str; }