使用 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 红包祝福语简短10字
18 周六早晨祝福语简短