第31天 写一个方法把0和1互转(0置1,1置0)
Activity
alery123456 commentedon May 17, 2019
二进制的话就可以异或了吧
undefinedYu commentedon May 17, 2019
var a;
!a && 1 || 0 ;
~a+2
ghost commentedon May 17, 2019
function interchange(x) {
return +!x;
}
qq674785876 commentedon May 20, 2019
~x + 2
tzjoke commentedon May 28, 2019
如果没其他更深层次的意思的话,,,
myprelude commentedon Jun 13, 2019
这个问题不清楚考察什么 ?
Damon99999 commentedon Jun 21, 2019
有问题
chenyouf1996 commentedon Jul 19, 2019
不考虑浮点数的话
function change(val) {
if (typeof val === 'number') {
val += ''
let newStrArr = val.split('').map((item, index) => {
return item == '1' ? '0' : '1'
})
let newStr = newStrArr.join('')
return parseInt(newStr)
}
return val.split('').map((item, index) => item == '1' ? '0' : '1').join('')
}
let str='10101'
console.log(change(str)) //01010
str=10101
console.log(change(str)) //1010
Lucenova commentedon Jul 25, 2019
应该是考察异或运算把,记得以前学过 1^num就可以完成,但是这仅仅限于num为数字的情况
FFairy commentedon Jul 25, 2019
function foo (val) {
var arr = val.split("");
var a = "";
for(let i=0;i<arr.length;i++){
if( arr[i] == 1){
a += 0;
}else if(arr[i] == 0){
a += 1;
}else{
a += arr[i]
}
}
console.log(a);
}
foo("48522220000333331111")
Vi-jay commentedon Jul 29, 2019
hc951221 commentedon Aug 7, 2019
function six(str) {
let arr = str.split('')
let brr = arr.map(item => {
if (item !== '0' && item !== '1') {
return item
} else if (item === '0') {
return 1
} else if (item === '1') {
return 0
} else if (item === ' ') {
return ' '
}
})
console.log(brr.join(''))
}
six(0110..32..1) // 1001..32..0
Konata9 commentedon Aug 25, 2019
感觉是二进制取反的操作,可以使用
~
符号进行取反。如果只是单纯的 0 和 1 互换的话。
zhuang13 commentedon Sep 13, 2019
直接异或操作就行了
ZindexYG commentedon Sep 18, 2019
15190408121 commentedon Sep 21, 2019
qiqingfu commentedon Jun 22, 2020
和
~x + 2
一样blueRoach commentedon Jun 30, 2020
smile-2008 commentedon Oct 9, 2020
function interchange(x) {
return +!x;
}
followfire commentedon Oct 12, 2020
reverse = (x: number) => x^1
YU-zhao-jun commentedon Nov 2, 2020
function test(str){
let length =str.length
let i = 0
let arr = []
const newStr = str.toString()
while(length>0){
if(!!+newStr[i]){
arr.push(0)
}else{
arr.push(1)
}
length--;
i++;
}
return arr
}
zxcdsaqwe123 commentedon Oct 20, 2021
//假设为字符串的1 0转换,数字的话使用toString就可以转为字符串,然后再外面套个parseInt就可以转会number类型
function changeNum(str) {
let arr = str.split('').map((x) => {
if (x === '0') {
return '1'
} else if (x === '1') {
return '0'
} else {
return x
}
})
let newstr = arr.reduce((x, y) => {
return x+y
})
return newstr
}
console.log(changeNum('1100011qwezx10'))
console.log('1100011qwezx10')
YangWenLong123 commentedon Nov 11, 2021
let a = 1;
//一般方法
if(a) {
a = 0;
} else {
a = 1;
}
//三木运算符
a = a ? 0 : 1;
//位运算
a ^= 1; --> 0
github-cxtan commentedon Feb 23, 2022
console.log(!0 ? 1 : 0);
console.log(~0 + 2);
github-cxtan commentedon Feb 23, 2022
console.log(!0 ? 1 : 0);
console.log(~0 + 2);
xiaoqiangz commentedon May 30, 2022
mark一下
PaleBlue0601 commentedon Sep 20, 2022
wangyuanjian commentedon Apr 6, 2023
我看了半天都没看到我经常用的方法
用1减去那个数就行了!