Golang程序以整数形式计数设置的位。
例子
例如,101、11、11011和1001001设置的位数分别为2、2、4和3。
解决这个问题的方法
步骤1-将数字转换为二进制表示形式。
步骤2-计算1的数量;返回计数。
示例
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.
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语