到达 0 链后如何停止遍历位(方向 = 从最低到最高有效位)?

问题描述 投票:0回答:1

我有这两个函数来遍历 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
导出它,即停止检查值的长度?

javascript loops binary
1个回答
0
投票
export function* walkBitsFromLSB(n: number) {
  while (n !== 0) {
    yield n & 1;
    n >>>= 1;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.