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.
极客教程