calgorithmbit-manipulation

Finding next bigger number with same number of set bits


I'm working on a problem where I'm given a number n, I have to find the next larger element with same number of set bits. While searching on Internet, I found an interesting piece of code which does this in few lines of code (BIT MAGIC) here:

unsigned nexthi_same_count_ones(unsigned a) {
  /* works for any word length */
  unsigned c = (a & -a);
  unsigned r = a+c;
  return (((r ^ a) >> 2) / c) | r;  // original typo corrected
}

But I want to understand the underlying logic about the algorithm that it will work always. All the boundary cases will be handled properly.

Can someone please explain the logic in simple steps.

Thanks


Solution

  • In the next higher number, the leftmost 1 of the rightmost run of 1s exchanges place with the 0 to its left, while the remaining 1s move to the far right.