[go语言算法] 求二进制整数中1的个数
2019-07-24 本文已影响0人
Ucan先生
package main
import "fmt"
func main() {
//count := getCountOfNotZero1(-1)
//count := getCountofNotZero3(-1);
count := getCountOfNotZero2(0)
fmt.Println(count);
}
//只适合正数
func getCountOfNotZero1(num int) int{
count := 0;
for ;num!=0 ; {
if num & 1>0 {
count++
}
num = num >>1;
}
return count;
}
func getCountOfNotZero2(num int) (count int){
flag := 1;
i := 2
for num != 0 && i<=64 {
if flag & num > 0 {
count++
}
flag <<= 1
i++;
fmt.Println(num)
}
return
}
func getCountofNotZero3(num int) int {
count := 0
for num != 0 {
num = num & (num-1)
count++;
}
return count
}