js与,或,异或
Bitwise Operations
A decimal number can be represented as a sequence of bits. To illustrate:
6 = 00000110 23 = 00010111
From the bitwise representation of numbers, we can calculate the bitwise AND, bitwise OR and bitwise XOR. Using the example above:
bitwiseAND(6, 23) ➞ 00000110 bitwiseOR(6, 23) ➞ 00010111 bitwiseXOR(6, 23) ➞ 00010001
Write three functions to calculate the bitwise AND, bitwise OR and bitwise XOR of two numbers.
Examples
bitwiseAND(7, 12) ➞ 4 bitwiseOR(7, 12) ➞ 15 bitwiseXOR(7, 12) ➞ 11
解法
与:2个条件同时为真时才为真,否则为假
或:2个条件只要有一个条件为真时为真
异或:2个条件相同时为
解法1
与
function bitwiseAND(n1, n2) {
const arr = []
let large = 0
let small = 0
if (n2 > n1) {
large = n2
small = n1
} else {
large = n1
small = n2
}
const num1 = large
.toString(2)
.split('')
.reverse()
const num2 = small
.toString(2)
.split('')
.reverse()
num1.forEach((item, index) => {
if (index + 1 > num2.length) {
arr.push(0)
} else {
if (item === num2[index]) {
arr.push(item)
} else {
arr.push(0)
}
}
})
arr.reverse()
return parseInt(arr.join(''), 2)
}
或
function bitwiseOR(n1, n2) {
const arr = []
let large = 0
let small = 0
if (n2 > n1) {
large = n2
small = n1
} else {
large = n1
small = n2
}
const num1 = large
.toString(2)
.split('')
.reverse()
const num2 = small
.toString(2)
.split('')
.reverse()
num1.forEach((item, index) => {
if (index + 1 > num2.length) {
arr.push(item)
} else {
if (item === num2[index]) {
arr.push(item)
} else {
arr.push(1)
}
}
})
arr.reverse()
return parseInt(arr.join(''), 2)
}
异或
function bitwiseXOR(n1, n2) {
const arr = []
let large = 0
let small = 0
if (n2 > n1) {
large = n2
small = n1
} else {
large = n1
small = n2
}
const num1 = large
.toString(2)
.split('')
.reverse()
const num2 = small
.toString(2)
.split('')
.reverse()
num1.forEach((item, index) => {
if (index + 1 > num2.length) {
arr.push(1)
} else {
if (item === num2[index]) {
arr.push(0)
} else {
arr.push(1)
}
}
})
arr.reverse()
return parseInt(arr.join(''), 2)
}
解法2
function bitwiseAND(n1, n2) {
return n1 & n2
}
function bitwiseOR(n1, n2) {
return n1 | n2
}
function bitwiseXOR(n1, n2) {
return n1 ^ n2
}