use*_*248 1 c numbers bit-manipulation
我需要生成所有2^(n-1) n-bit 数字,其中 biti始终是0并且j是可能数字的理论列表中数字的索引(按升序排列)。这是一个简单的表格,表示何时i从 0 变化到 2 n,并且为 3,因此j从 0 变化到 3。结果是一个 3 位数字,因此n为 3,可能的数字数量为 4。
j 0 1 2 3
i
0 0 2 4 6
1 0 1 4 5
2 0 1 2 3
Run Code Online (Sandbox Code Playgroud)
或者用二进制表示:
j 00 01 10 11
i
00 000 010 100 110 // The 1s place bit is not set in this line
01 000 001 100 101 // Ditto the 2s place bit
10 000 001 010 011 // Ditto the 4s place bit
Run Code Online (Sandbox Code Playgroud)
这是我能想到的最好的办法,除了简单地硬编码所有可能性:
unsigned result = (j&1)<<(i==0)|(j&2)<<(i!=2);
Run Code Online (Sandbox Code Playgroud)
但是,单独检查i比较并不能扩展,并且仅适用于上述表,不适用于n或的任意值i。
谁能想到一种更通用、更有效的方法来生成所有,特别是第j-位为 0 的第 -位n数字?i