In this tutorial, we will be discussing a program to find parity.
For this we will be provided with a number. Our task is to find its parity i.e count of whether the number of ones are odd or even.
Example
# include<bits/stdc++.h>
# define bool int
using namespace std;
//finding the parity of given number
bool getParity(unsigned int n) {
bool parity = 0;
while (n){
parity = !parity;
n = n & (n - 1);
}
return parity;
}
int main() {
unsigned int n = 7;
cout<<"Parity of no "<<n<<": "<<(getParity(n)? "Odd": "even");
getchar();
return 0;
}Output
Parity of no 7: odd