我有这两个函数来遍历 TypeScript 中整数的 32 位:
export function* walkBitsFromLSB(n: number) {
for (let i = 0; i < 32; i++) {
// Check the least significant bit (LSB)
const bit = (n >> i) & 1
yield bit
}
}
export function* walkBitsFromMSB(n: number) {
// Start with a mask that isolates the MSB of a 32-bit integer
let mask = 1 << 31
for (let i = 0; i < 32; i++) {
// Apply the mask to n and check if the result is non-zero
const bit = n & mask ? 1 : 0
yield bit
// Shift the mask right for the next bit
mask >>>= 1
}
}
我可以修改 MSB 使其仅遍历“相关”位,如下所示:
export function* walkRelevantBitsFromMSB(n: number) {
let mask = 1 << 31;
let start = false; // Flag to indicate when we've found the first non-zero bit
for (let i = 0; i < 32; i++) {
const bit = n & mask ? 1 : 0;
if (bit === 1) start = true;
if (start) yield bit; // Only start yielding bits after the first 1 is encountered
mask >>>= 1;
}
}
如何以某种最佳方式对LSB函数执行相同的操作?
也就是说,如果这些位是0b00000000000000000001111011101101
,您将读到:
1
0
1
1
0
1
1
1
0
1
1
1
1
DONE
如果不创建缓存/哈希图存储{ [binaryNumber]: length }
或任何类似的哈希表,你怎么能做到这一点呢?如何简单地从n
函数的输入中导出它,即停止检查值的长度?
1 个回答