How to check the parity of a number

Overview

The parity of a number is the number of one bit in the binary representation of the number.

There are two types of parity.

  • Even parity: The number contains an even number of one bit
  • Odd parity: The number contains an odd number of one bit

Example 1

  • Number: 11
  • Binary Representation: 1011

This number has odd parity because there are three one-bits in the binary representation of 11.

Example 2

  • Number: 10
  • Binary Representation: 1010

This number has even parity because there are two one-bits in the binary representation of 10.

Code

Follow these steps to check the parity of a given number:

  1. Create a Boolean flag called parityFlag that is initially set to false.

  2. Until the number is not equal to zero:

    • Unset the rightmost bit of the number using number & (number - 1).
    • Invert the parityFlag
import java.util.Scanner;
public class Main {
private static String checkParity(int number){
boolean parityFlag = false;
while(number != 0){
number &= (number - 1);
parityFlag = !parityFlag;
}
return parityFlag ? "Odd Parity":"Even Parity";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println("Parity of " + n + " - " + checkParity(n));
}
}

Enter the input below