Golang 程序用于查找给定数字的奇偶校验。

go programmingserver side programmingprogramming更新于 2025/5/10 10:37:17

定义 − 奇偶校验是指 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("%d 的二进制为:%s.\n", n, strconv.FormatInt(int64(n), 2))
   if FindParity(n){
      fmt.Printf("%d 的奇偶校验为奇数。\n", n)
   } else {
      fmt.Printf("%d 的奇偶性为偶。\n", n)
   }
}

输出

20 的二进制为:10100。
20 的奇偶性为偶。

相关文章