Golang程序可查找给定数字的奇偶校验。
定义-奇偶校验是指1的计数。如果1的计数是偶数,则它是偶数。如果1的计数为奇数,则奇偶校验为奇数。
例子
考虑n=20(00010100)
给定数字20的奇偶校验是偶数。
解决这个问题的方法
步骤1-定义一个方法,其中n和是一个参数,返回类型为int。
步骤2-计算给定数字位中的1s计数。
示例
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.
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下