Golang Program to find the parity of a given number.


Definition − Parity refers to the count of 1s. If count of 1s is even, then it’s even parity; and if the count of 1s is odd, then the parity is Odd.

Examples

Consider n = 20(00010100)

Parity of the given number 20 is even.

Approach to solve this problem

Step 1 − Define a method, where n and is an argument, return type is int.

Step 2 − Calculate the count of 1s in the given number’s bit.

Example

 Live Demo

package main
import (
   "fmt"
   "strconv"
)
func FindParity(n int) bool {
   parity := false
   for n != 0 {
      if n & 1 != 0{
         parity = !parity
      }
      n = n >> 1
   }
   return parity
}
func main(){
   n := 20
   fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2))
   if FindParity(n){
      fmt.Printf("Parity of the %d is Odd.\n", n)
   } else {
      fmt.Printf("Parity of the %d is Even.\n", n)
   }
}

Output

Binary of 20 is: 10100.
Parity of the 20 is Even.

Updated on: 17-Mar-2021

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements