使用 JavaScript 对具有偶数十进制值的二进制字符串进行排序
问题
我们需要编写一个JavaScript函数,该函数接受一个字符串,该字符串包含长度为3的二进制字符串,所有字符串都用空格分隔。
我们的函数应该按升序对数字进行排序,但只对偶数进行排序,并将所有奇数留在原处。
示例
以下是代码-
const str = '101 111 100 001 010';
const sortEvenIncreasing = (str = '') => {
const sorter = (a, b) => {
const findInteger = bi => parseInt(bi, 2);
if(findInteger(a) % 2 === 1 || findInteger(b) % 2 === 1){
return 0;
};
return findInteger(a) - findInteger(b);
};
const res = str
.split(' ')
.sort(sorter)
.join(' ');
return res;
};
console.log(sortEvenIncreasing(str));输出结果101 111 100 001 010
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短