I am having a small problem with the code below, instead of a number I am getting NaN. What's wrong?
for (var i = 0; i<100; i++) {
x = i ^ i
result = x + result;
}
var y = result - (result ^ result);
console.log(y);
I am having a small problem with the code below, instead of a number I am getting NaN. What's wrong?
for (var i = 0; i<100; i++) {
x = i ^ i
result = x + result;
}
var y = result - (result ^ result);
console.log(y);
It was
NaNbecause you did not initializeresultat the start.Let us see the script:
Here you are running the bitwise XOR for each
i. Since all the bits iniare equal to themselves,xwill always be 0.resultis 0 at the start and each time you add 0 to it, so as a result, at the end the value ofresultis 0.When you are XOR-ing
resultwith itself, then, again, all bits ofresultare equal to themselves, so the result will be 0.You are subtracting 0 from 0, resulting in 0.
A XOR B = A <> B
In bitwise level
A XOR B results in the result of the XOR on each bit.