Go 种群统计

种群统计:返回一个数字中被置位的个数(值为1)

package popcount

var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

2.3 使用循环重写PopCount来代替单个表达式

func PopCount(x uint64) int {
    var n = 0
    for i := uint(0); i < 8; i++ {
        n += int(pc[byte(x>>(i*8))])
    }
    return n
}

2.4 写一个用于统计位的PopCount, 它在其实际参数的64位上执行移位操作,每次判断最右边的位,进面实现统计功能

func PopCount(x uint64) int {
    var n = 0
    for i := uint(0); i < 64; i++ {
        n += int((x >> i) & 1)
    }
    return n
}

2.5 使用x&(x-1)可以清除x最右边的非零位,利用该特点写一个PopCount

func PopCount(x uint64) int {
    var n = 0
    for x != 0 {
        x = x & (x - 1)
        n++
    }
    return n
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容