- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements