且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找具有特定汉明重量的下一个数字

更新时间:2022-12-08 21:00:55

有以下三种情况:汉明权重(又称按位人口数)减少,不变或增加.

There are three cases: the Hamming weight (a.k.a. bitwise population count) is reduced, unchanged, or increased.

设置足够的连续低位0位以达到所需的权重.

Set enough successive low-order 0-bits to achieve the desired weight.

之所以起作用,是因为每个连续的低位是您可以添加的最小值,并且它们的和是可以充分增加汉明权重的最小差.

This works because each successive low-order bit is the smallest value that you can add, and their sum is the smallest difference that will sufficiently increase the Hamming weight.

  1. 添加最低位1位的值.
  2. 如有必要,增加上述汉明重量.

之所以起作用,是因为最低设置位的值是将引起进位的最低值.添加任何较低的位值只会设置该位,并增加汉明的权重.

This works because the value of the lowest set bit is the lowest value that will cause a carry to occur. Adding any lower bit-value would simply set that bit, and increase the Hamming weight.

只要加法运算符"1"将被清除.最终的重量必须等于或减小.如果由于一连串的进位而清除了几个位,则需要通过设置低位来增加补偿的权重.

As long as addition "carries a one," bits will be cleared. The resulting weight must be the equal or reduced. If several bits are cleared due to a chain of carries, you'll need to increase the weight in compensation by setting low-order bits.

  1. 清除足够的低位1位以达到所需的新权重.
  2. 按照上述步骤操作以保持体重不变.

之所以起作用,是因为清除低位1位会通过减去最小的可行量来找到具有所需权重的个数字.从正确权重的前一个数字开始,按照不变权重"算法到达下一个数字.

This works because clearing low-order 1-bits finds the preceding number with the desired weight, by subtracting the smallest viable amount. From the preceding number of the correct weight, follow the "unchanged weight" algorithm to reach the next number.