用位数组计算整数中1的个数

//
//  main.c
//  bitcounts
//
//  Created by Cheney Shen on 11-4-16.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#include <stdio.h>

static int bitcounts[] = 
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};

int bitcount(unsigned int u) {
    int n = 0;
    for(; u != 0; u >>= 4)
        n += bitcounts[u & 0x0f];
    return n;
}

int main (int argc, const char * argv[])
{
    return printf("%d", bitcount(1111111111111111111));
}
原文地址:https://www.cnblogs.com/shenfei2031/p/2017695.html