Mark As Completed Discussion

Check if an integer is even or odd without using division

This is Bitwise AND's territory: given integer x, the expression x & 1 will return 1 if the integer is odd, and 0 if it's even. This is because all odd numbers have their rightmost bit set to 1, and 1 & 1 = 1. Here's how you check 5 for oddity:

SNIPPET
1> 0b0101 & 0b0001 // same as 5 & 1
21

In various languages:

1let result = 0x5 & 0x1; // same as 5 & 1
2console.log(result);

For the sake or readability, you can even provide a nice wrapper around this simple operation:

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment