How to assess even and odd numbers using the bitwise operator &

Viewed 114

I am trying to assess if the numbers inside an array are even or odd using the bitwise operator &.

This is my code:

    arr = [1, 2, 4, 6, 9, 11, 18, 361, 5622, 5623]
    arr.forEach(function (el) {
        if (parseInt(el.toString(2)) & 1 === 0) {
            console.log(`${el} in binary is ${el.toString(2)} and it is an EVEN number`);
        } else {
            console.log(`${el} in binary is ${el.toString(2)} and it is an ODD number`);
        }
    });

Taking each element individually each one returns 0 or 1 which would assess if a number is even or odd, but in this case they all return ODD numbers. This is what I get as result:

1 in binary is 1 and it is an ODD number

2 in binary is 10 and it is an ODD number

4 in binary is 100 and it is an ODD number

and so on...

Where did I do wrong?

1 Answers

The order of operations matters here (and is defined by operator precedence). The & occurs after the === comparison, so your if-statement actually evaluates like:

if (parseInt(el.toString(2)) & (1 === 0)) {

where 1===0 is performed first. This will result in if(<num> & false), where false is converted to the numeric value 0 as it is being used in the context of the bitwise & operator. So, <num> & 0 will always evaluate to 0, which is a falsy value (thus always causing the else-block to trigger).

Instead, you can use parenthesis to enforce the order:

arr = [1, 2, 4, 6, 9, 11, 18, 361, 5622, 5623]
arr.forEach(function(el) {
  if ((el & 1) === 0) {
    console.log(`${el} in binary is ${el.toString(2)} and it is an EVEN number`);
  } else {
    console.log(`${el} in binary is ${el.toString(2)} and it is an ODD number`);
  }
});

You can also use the & operator on your number directly (so no need to use toString on it)

Related