給定一個未整理整數(每個4個八位字節)的數組,尋找具有至少一個'0'位的第一個元素的最佳方法是什麼,它是從LSB開始的索引。找到第一個可用位的最佳方法
e.g:其中n = 9
unsinged int uIntArray[] = {
0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
0xffffff9f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
};
答:
element's index = 4
bit's index = 4
我只能想到:
int main (void)
{
bool found_f = false;
int n = 9; //our test case value
unsigned int uIntArray[] = {
0xffffffff,
0xffffffff,
0xffffffff,
0xffffffff,
0xffffff8f,
0x00000000,
0x00000000,
0x00000000,
0x00000000,
};
unsigned int uIntBits [32] = {
1, 2, 4, 8, 16, 32, 64, 128,
256, 512, 1024, 2048, 4096, 8192, 16384, 32768,
65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648
};
unsigned int idx, jdx;
int ele_idx = -1;
int bit_idx = -1;
for (idx =0; idx < n; idx ++) {
if (uIntArray[idx] < UINT_MAX) { /* our candidate */
for (jdx =0; jdx < 32; jdx ++) {
if ((uIntBits[jdx] & uIntArray[idx])) {
ele_idx = idx;
bit_idx = jdx;
found_f = true;
break;
}
}
}
if(found_f) {
break;
}
}
fprintf (stderr, "\nEleIdx[%d] BitIdx[%d]\n", ele_idx, bit_idx);
return 0;
}
有沒有更好的辦法做到這一點?
你的邏輯可以收緊一點。 'found_f'是不必要的。數組也不是必需的。 – Skizz
首先,你聲明的第一個數組的正確答案是「(4,5)」而不是「(4,4)」。其次,您的實際代碼示例在數組中使用「0xffffff8f」值而不是原來的「0xffffff9f」,在這種情況下,正確的答案確實是「(4,4)」。不要混淆示例來混淆人們。 – AnT