Machine-translated by Google. Questions are authored in English.
Top

Discussion

Which Bitwise Operator can be used to check whether a number is EVEN or ODD quickly?

  • A.Bitwise AND (&)
  • B.Bitwise OR (|)
  • C.Bitwise XOR (^)
  • D.Bitwise NOT (~)

Answer: A

Correct answer: Bitwise AND (&)

Parity lives entirely in the lowest bit: a binary number is odd exactly when bit 0 is 1, because every higher place value is a multiple of two.

So n & 1 isolates that bit and answers the question in one operation - non-zero for odd, zero for even. It is faster than n % 2 and, unlike the modulus, gives the right answer for negative numbers in two's complement, where % returns \( -1 \) for an odd negative value. OR and XOR combine bits rather than isolating one, and ~ inverts the whole value.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.