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.
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短