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.

更新於: 2021 年 3 月 17 日

759 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.