|
1 |
| -/* Even Number: https://simple.wikipedia.org/wiki/Even_number |
| 1 | +/* |
| 2 | + * Even Number: https://simple.wikipedia.org/wiki/Even_number |
2 | 3 | *
|
3 | 4 | * function to check if number is even
|
4 | 5 | * return true if number is even
|
|
10 | 11 | * @return {boolean}
|
11 | 12 | */
|
12 | 13 |
|
13 |
| -const isEven = (number) => { |
14 |
| - return (number & 1) === 0 |
| 14 | +/* |
| 15 | + * Checking if number is even using divisibility by 2 |
| 16 | + * |
| 17 | + * If number is divisible by 2 i.e remainder = 0, then it is even |
| 18 | + * therefore, the function will return true |
| 19 | + * |
| 20 | + * If number is not divisible by 2 i.e remainder != 0, then it is not even i.e odd |
| 21 | + * therefore, the function will return false |
| 22 | + */ |
| 23 | + |
| 24 | +export const isEven = (number) => { |
| 25 | + return number % 2 === 0 |
15 | 26 | }
|
16 | 27 |
|
17 |
| -// testing |
18 |
| -console.log(isEven(4)) |
19 |
| -console.log(isEven(7)) |
| 28 | +/* |
| 29 | + * Checking if number is even using bitwise operator |
| 30 | + * |
| 31 | + * Bitwise AND (&) compares the bits of the 32 |
| 32 | + * bit binary representations of the number and |
| 33 | + * returns a number after comparing each bit: |
| 34 | + * |
| 35 | + * 0 & 0 -> 0 |
| 36 | + * 0 & 1 -> 0 |
| 37 | + * 1 & 0 -> 0 |
| 38 | + * 1 & 1 -> 1 |
| 39 | + * |
| 40 | + * For odd numbers, the last binary bit will be 1 |
| 41 | + * and for even numbers, the last binary bit will |
| 42 | + * be 0. |
| 43 | + * |
| 44 | + * As the number is compared with one, all the |
| 45 | + * other bits except the last will become 0. The |
| 46 | + * last bit will be 0 for even numbers and 1 for |
| 47 | + * odd numbers, which is checked with the use |
| 48 | + * of the equality operator. |
| 49 | + * |
| 50 | + * References: |
| 51 | + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND |
| 52 | + */ |
| 53 | + |
| 54 | +export const isEvenBitwise = (number) => { |
| 55 | + return (number & 1) === 0 |
| 56 | +} |
0 commit comments