1

I was given the task to figure out how to determine odd and even. I could not use %. I used & because I found it out on the internet but I couldn't find a decent for the way it works.

N/A

My sample I created was

`
    if ((22 & 1) === 0) { 
        return true;
    } else{
        return false;
    }`

Returns true

Edward
  • 21
  • 2
  • Possible duplicate of [Testing whether a value is odd or even](https://stackoverflow.com/questions/6211613/testing-whether-a-value-is-odd-or-even) – Kate Orlova Jul 14 '19 at 01:13

3 Answers3

3

The & bitwise operator works like this:

var isOdd = number & 1;
var isEven = !(number & 1);

(22 & 1) === 0 is true and so that tells you that it is even because number & 1 equals 0 if the number is even and 1 if the number is odd.

Rob Kwasowski
  • 2,690
  • 3
  • 13
  • 32
2

In binary notation the right-most bit is the ones place:

0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
6 = 0110
...etc

So as you can see every odd number ends in 1 and every even ends in 0.

When you use & you are making a bit-wise and calculation. When you do X & 1, are you comparing each bit of X against 1 or in binary: 00001 (you can keep extending the zeros to the left) and testing wether both bits are 1.

So for example 22 is 10110 in binary 22 & 1 looks each bit and test if both are true:

1 0 1 1 0
0 0 0 0 1 < no bits are 1 in both number
---------
0 0 0 0 0 < all zeros == 0  so 22 is even

23 is 10111:

1 0 1 1 1
0 0 0 0 1  the last bit is one in both numbers
---------
0 0 0 0 1 < 1 so 23 is odd

Since the last bit is always 1 in odd numbers x & 1 will always be one for odd numbers and zero for evens.

Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    This should be the accepted answer. Understanding bitwise operators in JavaScript requires an understanding of the binary representation of numbers. – trevor Jul 14 '19 at 01:33
  • This was best description I've found so far. Thank you – Edward Jul 14 '19 at 01:43
0
function isEven(number) {
  return (number & 1) == 0;
}
const userInput = 4;
console.log(isEven(userInput) == true ? "Even" : "Odd");
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29