How to check if a number is even without using the % or modulo operator?
We can use the bitwise AND&
operator for this problem. The &
operates on its operand and treats them as binary values and performs the AND operation.
function isEven(num) {
if (num & 1) {
return false;
} else {
return true;
}
};
0
in binary is 000.1
in binary is 001.2
in binary is 010.3
in binary is 011.4
in binary is 100.5
in binary is 101.6
in binary is 110.7
in binary is 111.
and so on...
a |
b |
a & b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
So when we console.log
this expression 5 & 1
it returns 1
. Ok, first the &
operator converts both numbers to binary so 5
turns to 101 and 1
turns to 001.
Then it compares every bit (0's and 1's) using the bitwise AND operator. 101 &
001. As we can see from the table the result can be only 1
if a
AND b
are 1
.
101 & 001 |
---|
101 |
001 |
001 |
- So first we compare the left most bit
1
&
0
the result should be0
. - Then we compare the middle bit
0
&
0
the result should be0
. - Then we compare the last bit
1
&
1
the result should be1
. - Then the binary result
001
will be converted to a decimal number which will be1
.
If we console.log
this expression 4 & 1
it will return 0
. Knowing the last bit of 4
is 0
and 0 & 1
will be 0
. If you have a hard time understand this we could use a recursive function to solve this problem.
function isEven(num) {
if (num < 0 || num === 1) return false;
if (num == 0) return true;
return isEven(num - 2);
}