Obviously is the XOR-operator is used in low-level programming-languages used a lot for setting a value back to all bits 0.
For example:
11010 ^ 11010 => 00000
Brought my teacher to figuring a out few exercises.
One is: "Set the bits of a number back to 0 by using just the bitwise AND (&) and the bitwise NOT (~) operators."
I've got now this solution:
let readline = require('readline-sync');
const limit = 100;
// THAT THE PART WHICH IS IMPORTANT TO ME !!
function setNumberToNull(num) {
// First invert the bits of the number.
// Then compare every bit with the not
// inverted number using an bitwise and.
return num & (~num);
}
// ########################################
function testSetNumberToNull(limit) {
let i;
for (i = 0; i < limit; i++) {
let testNum = Math.floor(Math.random() * 10000);
let tmp = setNumberToNull(testNum);
if (tmp) {
return { test : i, message : testNum + ' caused failure.' };
}
}
return { test : i, message : 'All tests passed.'};
}
console.log(testSetNumberToNull(limit).message);
I works fine. Nevertheless I would appreciate your review.
ReferenceError: require is not defined
. – zyabin101 Jun 26 at 10:06readline
should also beconst
. – gcampbell Jun 26 at 11:11