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.
廣告