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.