【模板】popcount

posted on 2022-02-04 18:11:33 | under 模板 | source

int popcount(int x){
    #define BIT2(n) n,n+1,n+1,n+2
    #define BIT4(n) BIT2(n),BIT2(n+1),BIT2(n+1),BIT2(n+2)
    #define BIT6(n) BIT4(n),BIT4(n+1),BIT4(n+1),BIT4(n+2)
    #define BIT8(n) BIT6(n),BIT6(n+1),BIT6(n+1),BIT6(n+2)
    static const char popc[1<<8]={BIT8(0)};
    return popc[x&0xff]+popc[x>>8&0xff]+popc[x>>16&0xff]+popc[x>>24&0xff];
}
int popcount(int x){return x?popcount(x&x-1)+1:0;}
posted @ 2022-11-06 19:11  caijianhong  阅读(79)  评论(0编辑  收藏  举报