
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
Finding the Parity of a Number Efficiently in C++
In this tutorial, we are going to write a program that finds the parity of a number.
We can find the parity of a number efficiently by performing the following operations using xor and right-shift operators.
int b; b = n ^ (n >> 1); b = b ^ (b >> 2); b = b ^ (b >> 4); b = b ^ (b >> 8); b = b ^ (b >> 16);
If the last bit of the result is 1 then it's an odd parity else even parity.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; void findParity(int n) { int b; b = n ^ (n >> 1); b = b ^ (b >> 2); b = b ^ (b >> 4); b = b ^ (b >> 8); b = b ^ (b >> 16); if ((b & 1) == 0) { cout << "Even Parity" << endl; } else { cout << "Odd Parity" << endl; } } int main() { int n = 15; findParity(n); return 0; }
Output
If you run the above code, then you will get the following result.
Even Parity
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements