EPI 4.1: Computing The Parity Of A Word In Python - Version 2
Elements Of Programming Interviews Python. How to compute parity of binary word Version 2 with a bit fiddling trick. X & (X-1)
We are looking at question 4.1 from Elements Of Programming Interviews Book. If you are applying for software engineering positions I highly recommend getting this book.
4.1 Computing the parity of a word
The parity of a binary word is 1 if the number of 1s i n the word is odd; otherwise, it is 0. For example, the parity of 1011 is 1, and the parity of 1000010000 is 0. Parity checks are used to detect single bit errors in data storage and communication. It is fairly straight forward to write code that computes the parity of a single 64-bit word.
Here is the video I created which walk you through solution provided in the book.
def parity_v2(x):
result = 0;
while x:
result ^= 1
x &= x-1
return result