title: Finding next bigger number with same number of set bits
body: <p>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) <a href="http://www.cl.cam.ac.uk/~am21/hakmemc.html#item175" rel="noreferrer">here</a>:</p>
  
  <pre><code>unsigned nexthi_same_count_ones(unsigned a) {
    /* works for any word length */
    unsigned c = (a &amp; -a);
    unsigned r = a+c;
    return (((r ^ a) &gt;&gt; 2) / c) | r);
  }
  </code></pre>
  
  <p>But I want to understand the underlying logic about the algorithm that it will work always. All the boundary cases will be handled properly. </p>
  
  <p>Can someone please explain the logic in simple steps.</p>
  
  <p>Thanks</p>