Program to find parity in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

# 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
raja
Published on 19-May-2020 15:08:19
Advertisements