Find next number with specific hamming weight

前端 未结 1 1557
清歌不尽
清歌不尽 2021-01-23 05:13

Given a certain integer x, I wish to compute the next higher integer y which has a certain hamming weight w.

相关标签:
1条回答
  • 2021-01-23 05:48

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

    Increased Hamming weight

    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.

    Unchanged Hamming weight

    1. Add the value of the lowest-order 1-bit.
    2. Increase the Hamming weight per above, if necessary.

    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.

    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.

    Reduced Hamming weight

    1. Clear enough low-order 1-bits to achieve the new desired weight.
    2. Follow the above process for unchanged weight.

    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.

    0 讨论(0)
提交回复
热议问题