Parity: Parity of a number refers to whether it contains an odd or even number of 1-bits. The number has “odd parity”, if it contains odd number of 1-bits and is “even parity” if it contains even number of 1-bits.
Main idea of the below solution is – Loop while n is not 0 and in loop unset one of the set bits and invert parity.
Algorithm: getParity(n) 1. Initialize parity = 0 2. Loop while n != 0 a. Invert parity parity = !parity b. Unset rightmost set bit n = n & (n-1) 3. return parity Example: Initialize: n = 13 (1101) parity = 0 n = 13 & 12 = 12 (1100) parity = 1 n = 12 & 11 = 8 (1000) parity = 0 n = 8 & 7 = 0 (0000) parity = 1
Parity of no 7 = odd
Above solution can be optimized by using lookup table. Please refer to Bit Twiddle Hacks[1st reference] for details.
Time Complexity: The time taken by above algorithm is proportional to the number of bits set. Worst case complexity is O(Log n).
Uses: Parity is used in error detection and cryptography.
http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive – last checked on 30 May 2009.
- Finding the Parity of a number Efficiently
- Compute the parity of a number using XOR and table look-up
- Find position of the only set bit
- Swap all odd and even bits
- Binary representation of a given number
- Multiply a given Integer with 3.5
- Count number of bits to be flipped to convert A to B
- Count set bits in an integer
- Write an Efficient C Program to Reverse Bits of a Number
- Position of rightmost set bit
- Program to find whether a no is power of two
- Efficient way to multiply with 7
- Write a program to reverse digits of a number
- Write an Efficient Method to Check if a Number is Multiple of 3
- Smallest power of 2 greater than or equal to n