如果你有足够的内存可以用来计算O(1)中数字的二进制表示中1的数量的有效方法.这是我在网上论坛上发现的一个面试问题,但没有答案.有人可以提出一些建议,我想不出在O(1)时间内做到这一点的方法吗?
060*_*002 43
我有一个解决方案,计算O(Number of 1's)时间位:
bitcount(n):
count = 0
while n > 0:
count = count + 1
n = n & (n-1)
return count
Run Code Online (Sandbox Code Playgroud)
在最坏的情况下(当数字是2 ^ n - 1时,所有1都是二进制的)它将检查每一位.
编辑:刚刚为bitcount找到了一个非常好的恒定时间,常量内存算法.在这里,用C语言写成:
int BitCount(unsigned int u)
{
unsigned int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里找到它的正确性证明.
Sri*_*adi 17
请注意以下事实:n&(n-1)总是消除最不重要的1.
因此我们可以编写用于计算1的数量的代码,如下所示:
count=0;
while(n!=0){
n = n&(n-1);
count++;
}
cout<<"Number of 1's in n is: "<<count;
Run Code Online (Sandbox Code Playgroud)
程序的复杂性将是:n的1的数量(总是<32).
小智 15
我从另一个网站看到了以下解决方案:
int count_one(int x){
x = (x & (0x55555555)) + ((x >> 1) & (0x55555555));
x = (x & (0x33333333)) + ((x >> 2) & (0x33333333));
x = (x & (0x0f0f0f0f)) + ((x >> 4) & (0x0f0f0f0f));
x = (x & (0x00ff00ff)) + ((x >> 8) & (0x00ff00ff));
x = (x & (0x0000ffff)) + ((x >> 16) & (0x0000ffff));
return x;
}
Run Code Online (Sandbox Code Playgroud)
小智 10
public static void main(String[] args) {
int a = 3;
int orig = a;
int count = 0;
while(a>0)
{
a = a >> 1 << 1;
if(orig-a==1)
count++;
orig = a >> 1;
a = orig;
}
System.out.println("Number of 1s are: "+count);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
下面是两个简单的示例(C++ 语言),您可以通过它们来执行此操作。
__builtin_popcount()。int numOfOnes(int x) {
return __builtin_popcount(x);
}
Run Code Online (Sandbox Code Playgroud)
int hammingDistance(int x) {
int count = 0;
for(int i = 0; i < 32; i++)
if(x & (1 << i))
count++;
return count;
}
Run Code Online (Sandbox Code Playgroud)
countBits(x){
y=0;
while(x){
y += x & 1 ;
x = x >> 1 ;
}
}
Run Code Online (Sandbox Code Playgroud)
而已?
| 归档时间: |
|
| 查看次数: |
136971 次 |
| 最近记录: |