算法之二进制数中1的个数

xiaoxiao2021-02-28  82

int numTable[256] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; //摘自《数学之美》 int numOfOne(int v) { int number = 0; while(v) { if(v % 2 == 1) { number++; } v >>= 1; } return number; } unsigned int numOfOne2(unsigned int n) { unsigned int count = 0; while(n > 0) { ++count; n = n & (n-1); } return count; } unsigned int hammingWeight(unsigned int n) { unsigned int t = n; t = (t & 0x55555555) + ( (t & 0xAAAAAAAA) >> 1); t = (t & 0x33333333) + ( (t & 0xCCCCCCCC) >> 2); t = (t & 0x0f0f0f0f) + ( (t & 0xf0f0f0f0) >> 4); t = (t & 0x00ff00ff) + ( (t & 0xff00ff00) >> 8); t = (t & 0x0000ffff) + ( (t & 0xffff0000) >> 16); return t; } void main() { int a = 255; printf("%d,%d,%d,%d\n", numTable[a], numOfOne(a), numOfOne2(a), hammingWeight(a)); }
转载请注明原文地址: https://www.6miu.com/read-52489.html

最新回复(0)