The parity of a number is the number of one bit in the binary representation of the number.
There are two types of parity.
This number has odd parity because there are three one-bits in the binary representation of 11.
This number has even parity because there are two one-bits in the binary representation of 10.
Follow these steps to check the parity of a given number:
Create a Boolean flag called parityFlag
that is initially set to false
.
Until the number is not equal to zero:
number & (number - 1)
.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