Golang 程序,查找给定数字的奇偶校验。
定义 − 奇偶校验指 1 的数目。如果 1 的数目为偶数,则为偶数奇偶校验;如果 1 的数目为奇数,则为奇数奇偶校验。
示例
考虑 n = 20(00010100)
给定数字 20 的奇偶校验为偶数。
解决此问题的方法
步骤 1 − 定义一个方法,其中 n 和是一个参数,返回类型为 int。
步骤 2 − 计算给定数字比特中 1 的数目。
示例
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)
}
}输出
Binary of 20 is: 10100. Parity of the 20 is Even.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP