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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the maximum sum pair in an Array with even parity
- Sum of elements from an array having even parity
- Longest alternative parity subsequence
- Finding the Parity of a number Efficiently
- Parity of the given mathematical expression using given N numbers
- Compute the parity of a number using XOR and table look-up
- Query to count odd and even parity elements in subarray after XOR with K
- Count of all subsequences having adjacent elements with different parity
- Count numbers which can be represented as sum of same parity primes
- Count of all possible pairs of array elements with same parity
- Range Queries for finding the Sum of all even parity numbers
- Minimum integer that can be obtained by swapping adjacent digits of different parity
- Range Queries to count the number of even parity values with updates
- Check if matrix A can be converted to B by changing parity of corner elements of any submatrix
- Minimum flips in a Binary array such that XOR of consecutive subarrays of size K have different parity
- Minimum operations required to modify the array such that parity of adjacent elements is different
- Remove all even parity nodes from a Doubly and Circular Singly Linked List
- Construct a square Matrix whose parity of diagonal sum is same as size of matrix
- Program to find sum of 1 + x/2! + x^2/3! +...+x^n/(n+1)!
- Program to find value of 1^k + 2^k + 3^k + ... + n^k