我正在尋找比以下更快的算法。給定一個64位無符號整數序列,返回序列中設置的每個64位的次數。計算無符號長整數中的常見位
例子:
4608 = 0000000000000000000000000000000000000000000000000001001000000000
4097 = 0000000000000000000000000000000000000000000000000001000000000001
2048 = 0000000000000000000000000000000000000000000000000000100000000000
counts 0000000000000000000000000000000000000000000000000002101000000001
例子:
2560 = 0000000000000000000000000000000000000000000000000000101000000000
530 = 0000000000000000000000000000000000000000000000000000001000010010
512 = 0000000000000000000000000000000000000000000000000000001000000000
counts 0000000000000000000000000000000000000000000000000000103000010010
目前我使用的是相當明顯的,幼稚的做法:
static int bits = sizeof(ulong) * 8;
public static int[] CommonBits(params ulong[] values) {
int[] counts = new int[bits];
int length = values.Length;
for (int i = 0; i < length; i++) {
ulong value = values[i];
for (int j = 0; j < bits && value != 0; j++, value = value >> 1) {
counts[j] += (int)(value & 1UL);
}
}
return counts;
}
您在64位操作系統上運行的權利? – 2009-10-05 02:42:38
我的新想法將速度提高了8倍? – 2009-10-05 02:59:24
@ csharptest.net:是的,Windows 7 x64。 – jason 2009-10-05 12:05:02