例如,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.