Given an integer N. The task is to write a program to find the parity of the given number.
Note: Parity of a number is used to define if the total number of set-bits(1-bit in binary representation) in a number is even or odd. If the total number of set-bits in the binary representation of a number is even then the number is said to have even parity, otherwise, it will have odd parity.
Input : N = 13 Output : Odd Parity Binary representation of 13 is (1101) Input : N = 9 (1001) Output : Even Parity
The parity of a number represented by 32-bits can be efficiently calculated by performing the following operations.
Let the given number be x, then perform the below operations:
- y = x^(x>>1)
- y = y^(y>>2)
- y = y^(y>>4)
- y = y^(y>>8)
- y = y^(y>>16)
Now, the rightmost bit in y will represent the parity of x. If the rightmost bit is 1, then x will have odd parity and if it is 0 then x will have even parity.
So, in order to extract the last bit of y, perform bit-wise AND operation of y with 1.
if(y&1==1) odd Parity else even Parity
Below is the implementation of the above approach:
Even Parity Odd Parity
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.
- Range Queries for finding the Sum of all even parity numbers
- Program to invert bits of a number Efficiently
- Compute the parity of a number using XOR and table look-up
- Range Queries to count the number of even parity values with updates
- Finding powers of any number P in N!
- How to use unordered_map efficiently in C++
- Efficiently check whether n is a multiple of 4 or not
- Writing C/C++ code efficiently in Competitive programming
- Program to find parity
- Sum of elements from an array having even parity
- Efficiently check if a string has all unique characters without using any additional data structure
- Find the maximum sum pair in an Array with even parity
- Count of odd and even parity elements in subarray using MO's algorithm
- Count the nodes in the given tree whose weight is even parity
- Query to count odd and even parity elements in subarray after XOR with K
- Efficiently find first repeated character in a string without using any additional data structure in one traversal
- Remove all even parity nodes from a Doubly and Circular Singly Linked List
- 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
- std::gcd | C++ inbuilt function for finding GCD
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.