我得到了问题的答案,从这里计数组数位数。使用带有无限内存的K&R方法计算比特数
How to count the number of set bits in a 32-bit integer?
long count_bits(long n) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; n; c++)
n &= n - 1; // clear the least significant bit set
return c;
}
它是简单也理解。并找到最好的答案作为布赖恩Kernighans方法,张贴hoyhoy ......并在最后添加以下内容。
请注意,这是访谈中使用的一个问题。面试官会补充说明你有“无限记忆”。在这种情况下,您基本上会创建一个大小为232的数组,并在每个位置填写数字的位数。然后,这个函数变成O(1)。
有人可以解释如何做到这一点?如果我有无限的记忆...