
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Parity of a Number Efficiently in C++
In this article, we will be discussing a program to find the parity of a given number N.
Parity is defined as the number of set bits (number of ‘1’s) in the binary representation of a number.
If the number of ‘1’s in the binary representation are even, the parity is called even parity and if the number of ‘1’s in the binary representation is odd, the parity is called odd parity.
If the given number is N, we can perform the following operations.
- y = N ^ (N >> 1)
- y = y ^ (y >> 2)
- y = y ^ (y >> 4)
- y = y ^ (y >> 8)
- y = y ^ (y >> 16)
Once all these operations are done, the rightmost bit in y will represent the parity of the number. If the bit is 1, the parity would be odd and if the bit would be 0, the parity will be even.
Example
#include <bits/stdc++.h> using namespace std; bool calc_parity(int N) { int y; y= N ^ (N >> 1); y = y ^ (y >> 2); y = y ^ (y >> 4); y = y ^ (y >> 8); y = y ^ (y >> 16); //checking the rightmost bit if (y & 1) return 1; return 0; } int main() { int n=1345; int result = calc_parity(n); if(result==1) cout << "Odd Parity" << endl; else cout << "Even Parity" << endl; return 0; }
Output
Even Parity
Advertisements