How to determine the parity of a number in Python using bitwise operations?

    1 answer 1

    Option # 1 (the easiest):

    x = 5 if x & 1: print "Наш x - нечетный" else: print "Наш x - четный" 

    Everything is simple here, we compare our binary representation 5 ( 101 ) with binary representation 1 ( 001 ), through bitwise I. As a result, we get 001 , which will be greater than zero, which means the last symbol in binary representation is 1 (the whole essence of such a test, find out , the last character is 1 (odd) or 0 (even).

    Option # 2 (interesting):

    See it. There is a bit shift operation.

     x = 5 x >> 1 # = 2; равносильно делению на 2 без остатка x << 1 # = 10; равносильно умножению на 2 

    Given this, you can check this:

     x = 5 y = x >> 1 if x == (y << 1): print "Наш x - четный" else: print "Наш x - нечетный" 

    To understand how the bit shift works, you need to remember that numbers are represented by zeros and ones. Our x is 5 , then its binary representation will be: 101 .

    The right shift ( >> ) is, one can say, the removal of the number of zeros or ones on the right of the binary representation of the corresponding number after the operator. In our case - 1. That is. it turns out 10 , which corresponds to 2 in decimal representation.

    A left shift is the addition of zeros to the right. We, as if moving the binary representation to the left, by N characters, these N characters are filled with zeros. Those. the resulting 10 we "shift by 1", and we get 100 , which corresponds to the 4th in decimal form. As a result, we in if will be a comparison of the numbers 4 and 5 .

    • Thanks a lot, it helped a lot - Vlad Stepanov