题解 | #字符串合并处理#
字符串合并处理
https://www.nowcoder.com/practice/d3d8e23870584782b3dd48f26cb39c8f?tpId=37&tqId=21253&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
const rl = require("readline").createInterface({ input: process.stdin });
rl.on("line", (line) => {
// 1、首先进行合并字符串
let str = line.replaceAll(" ", "");
// 2、对合并后的字符串进行排序
let arr = str.split("");
// console.log(arr)
let arrJ = [];
let arrO = [];
arr.forEach((item, index) => {
if (index % 2 == 0) {
arrJ.push(item);
} else {
arrO.push(item);
}
});
arrJ.sort();
arrO.sort();
arr.forEach((item, index) => {
if (index % 2 == 0) {
arr[index] = arrJ.shift();
} else {
arr[index] = arrO.shift();
}
});
// console.log(arr)
// 3、进行转换操作
arr.forEach((item, index) => {
// if (/[a-f]/i.test(item)) {
// arr[index] = parseInt(
// parseInt(arr[index], 16)
// .toString(2)
// .padStart(4, "0")
// .split("")
// .reverse()
// .join(""),
// 2
// ).toString(16);
// if (/[a-f]/i.test(arr[index])) {
// arr[index] = arr[index].toUpperCase();
// }
// } else if (/\d/.test(item)) {
// arr[index] = parseInt(
// (+arr[index])
// .toString(2)
// .padStart(4, "0")
// .split("")
// .reverse()
// .join(""),
// 2
// ).toString(16);
// if (/[a-f]/i.test(arr[index])) {
// arr[index] = arr[index].toUpperCase();
// }
// }
//10进制转化为2进制后会少0(十进制数0-9除了8、9其余转化后都会少0),因此需要补够4位二进制,前补0,这是一个坑,不然翻转之后会出现错误
if (/[a-f0-9]/i.test(item)) {
arr[index] = parseInt(
parseInt(arr[index], 16)
.toString(2)
.padStart(4, "0")
.split("")
.reverse()
.join(""),
2
).toString(16);
if (/[a-f]/i.test(arr[index])) {
arr[index] = arr[index].toUpperCase();
}
}
});
// 将arr数组转为字符串输出
str = arr.join("");
console.log(str);
});