Go语言程序用于统计整数中的位集。
示例
例如,101、11、11011 和 1001001 的位集计数分别为 2、2、4 和 3。
解决此问题的思路
步骤 1 − 将数字转换为二进制表示法。
步骤 2 − 统计 1 的数量;返回 count。
示例
package main
import (
"fmt"
"strconv"
)
func NumOfSetBits(n int) int{
count := 0
for n !=0{
count += n &1
n >>= 1
}
return count
}
func main(){
n := 20
fmt.Printf("Binary representation of %d is: %s.\n", n,
strconv.FormatInt(int64(n), 2))
fmt.Printf("The total number of set bits in %d is %d.\n", n, NumOfSetBits(n))
}输出
Binary representation of 20 is: 10100. The total number of set bits in 20 is 2.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP