Solution Review: Check If Number Is Even/Odd

Here, we see the solution for checking if a number is even/odd.

Solution review

We need to go through all the elements to check if any are even/Odd.

It would be best if you saw the pattern of bits present in odd numbers. If you take a closer look at each of them, you can see the right-most significant bit is set to 1 (for 202^{0} place).

So, we do an AND bitwise operation with 1 decimal number to see if the resultant output is 1. If not, it is an even number else odd.

Algorithm

  • Iterate over all the elements, to check

  • if (element & 1) == 1

    • if true, print "Odd"
    • else, print "Even"

Explanation

Table illustrating values at various levels of each operation.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.