这是两种算法的组合,它迭代的次数与设置的位数一样多:
unsigned count_low_zerobits(unsigned n) {
static const unsigned MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
return MultiplyDeBruijnBitPosition[((n & -n) * 0x077CB531U) >> 27];
}
unsigned find_bits(unsigned n, unsigned positions[]) {
unsigned c;
for (c = 0; n; c++) {
unsigned bitnum = count_low_zerobits(n); // get bit number of lowest bit
positions[c] = bitnum; // put number to positions array
n ^= 1 << bitnum; // use XOR to unset just this one bit
}
return c;
}
有关更多信息的参考count_low_zerobits
:问题的答案设置的最低有效位的位置。
然后函数find_bits
简单地调用它,将给定的位位置放入结果数组,并使用它使用按位异或来取消设置该位。
最后,为了方便起见,我用一段丑陋的代码来测试这个:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
unsigned positions[128] = {0};
int testnumber = 4442344;
unsigned count = find_bits(testnumber, positions);
// non-standard, leaking one-liner for debug purposes, remove if fails to compile:
printf ("Number in binary: %s\n", itoa(testnumber, malloc(129), 2));
printf("%u bits: ", count);
for(unsigned i = 0 ; i < count ; ++i) {
printf("%u ", positions[i]);
}
printf("\n");
return 0;
}