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
NaN
because you did not initializeresult
at the start.Let us see the script:
Here you are running the bitwise XOR for each
i
. Since all the bits ini
are equal to themselves,x
will always be 0.result
is 0 at the start and each time you add 0 to it, so as a result, at the end the value ofresult
is 0.When you are XOR-ing
result
with itself, then, again, all bits ofresult
are 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.