如果您有足够的内存来处理,高效计算一个数字的二进制表示中1的数量的方法是O(1)。这是我在一个在线论坛上找到的面试问题,但没有答案。有人能提供一些建议吗?我无法想出如何在O(1)时间内完成。
如果您有足够的内存来处理,高效计算一个数字的二进制表示中1的数量的方法是O(1)。这是我在一个在线论坛上找到的面试问题,但没有答案。有人能提供一些建议吗?我无法想出如何在O(1)时间内完成。
我有一个解决方案,可以在O(Number of 1's)
的时间内计算位数:
bitcount(n):
count = 0
while n > 0:
count = count + 1
n = n & (n-1)
return count
最坏情况下(当数字为2^n - 1,二进制中全部为1时),它将检查每个比特位。
编辑:刚找到一个非常好的恒定时间、恒定内存的位计数算法。以下是用C语言编写的代码:
int BitCount(unsigned int u)
{
unsigned int uCount;
uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}
你可以在这里找到其正确性的证明。
count=0;
while(n!=0){
n = n&(n-1);
count++;
}
cout<<"Number of 1's in n is: "<<count;
程序的复杂度将是:n 中1的数量(始终 < 32)。我从另一个网站上看到了以下解决方案:
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;
}
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);
}
if (orig & 1)
count++;
orig >>= 1;
- Chang Hyun Parkcount += orig & 1;
orig >>= 1;
- Noah countBits(x){
y=0;
while(x){
y += x & 1 ;
x = x >> 1 ;
}
}
就这样了吗?
以下是两个简单的例子 (使用 C++),其中之一可以实现这个目标。
__builtin_popcount()
来简单地计算设置位(1)的数量。int numOfOnes(int x) {
return __builtin_popcount(x);
}
int hammingDistance(int x) {
int count = 0;
for(int i = 0; i < 32; i++)
if(x & (1 << i))
count++;
return count;
}
int numberOfOneBitsInInteger(int input) {
int numOneBits = 0;
int currNum = input;
while (currNum != 0) {
if ((currNum & 1) == 1) {
numOneBits++;
}
currNum = currNum >> 1;
}
return numOneBits;
}
public static int numOnesInBinary(int n) {
if (n < 0) return -1;
int j = 0;
while ( n > Math.pow(2, j)) j++;
int result = 0;
for (int i=j; i >=0; i--){
if (n >= Math.pow(2, i)) {
n = (int) (n - Math.pow(2,i));
result++;
}
}
return result;
}
nofone(int x) {
a=0;
while(x!=0) {
x>>=1;
if(x & 1)
a++;
}
return a;
}