题解 | #字符串合并处理#
字符串合并处理
http://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f
字符串合并处理:C语言解法
#include<stdio.h>
int cmp(char *a, char *b){
return (int)(*a-*b);
}
char reverse(int num){
int re_num = 0;
char re_char = 0;
int bit[4] = {0};
for(int i=0; i<4; i++){
bit[i] = num%2;
num=num/2;
}
for(int i=0; i<4; i++){
//对二进制数进行翻转并计算
re_num += bit[3-i]*(int)pow(2,i);
}
if(re_num>=0 && re_num<=9)
re_char = re_num + '0';
else if(re_num>=10 && re_num<=15)
re_char = re_num-10+'A';
return re_char;
}
void convert(char *str){
int len = strlen(str);
int num = len/2;
char str0[num];
char str1[len-num-1];
memset(str0, 0, num);
memset(str1, 0, len-num-1);
//第一步:将输入的两个字符串str1和str2进行前后合并
for(int i=0,j=0; i<len; i++){
if(str[i] == ' ')
j++;
str[i] = str[j++];
}
//第二步:对合并后的字符串进行排序
for(int i=0,j=0; i<len-1; i++){
if(i%2)
str1[j++] = str[i];
else
str0[j] = str[i];
}
qsort(str0, num, sizeof(char), cmp);
qsort(str1, len-num-1, sizeof(char),cmp);//排序数组的长度要给精确的值
for(int i=0,j=0; i<len-1; i++){
if(i%2)
str[i] = str1[j++];
else
str[i] = str0[j];
}
//第三步:对排序后的字符串中的'0'~'9'、'A'~'F'和'a'~'f'字符,需要进行转换操作
for(int i=0; i<len-1; i++){
int temp = 16;
if(str[i]>='A' && str[i]<='F'){
temp = str[i]-'A'+10;
}else if(str[i]>='a' && str[i]<='f'){
temp = str[i]-'a'+10;
}else if(str[i]>='0' && str[i]<='9'){
temp = str[i]-'0';
}
if(temp != 16)
str[i] = reverse(temp);
}
printf("%s\n",str);
}
int main(){
char str[200] = {""};
while(gets(&str)){
convert(str);
}
}