TITLE: What is the next number having the same number of bit 1s?
QUESTION [6 upvotes]: You are given a number, $A$, and you have to determine a number, $B$, such that $B>A$ and the number of $1's$ in the binary representation of $A =$ number of $1's$ in the binary representation of $B$.
What is the smallest $B$?

REPLY [4 votes]: This problem actually shows up in the list of bit twiddling hacks as Next Permutation.
In C++:
t = A | (A - 1);
B = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(A) + 1)); 

__builtin_ctz(A) is the number of trailing zeros of A, or the largest power of 2 that divides A.
Going through the example in Rory's answer, if A == 011100, then:
t = A | (A - 1) = 011100 | 011011 = 011111

B = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(A) + 1))
  = (100000) | (((11111111 11100000 & 00000000 00100000) - 1) >> (2 + 1))
  = (100000) | (((100000 - 1) >> 3))
  = (100000) | (11111 >> 3)
  = (100000) | (11)
  = 100011

As a bit of explanation. Let's consider that A looks like:
X0[..1..][..0..]
     p      q

Where X are arbitrary bits followed by a 0, p 1s, and q 0s, where p > 0 but q doesn't have to be (in the original example, X is empty, p is 3, and q is 2). Given that, t is:
             t = X0[..1..][..1..]   // turn on all trailing bits of A
                      p      q

           t+1 = X1[..0..][..0..]
                      p      q

            ~t = Y1[..0..][..0..]  // where Y = ~X
                      p      q

    (~t & -~t) =  1[..0..][..0..]  // "freeze" the right-most 1-bit of ~t
                      p      q

(~t & -~t) - 1 =  0[..1..][..1..]
                      p      q

So when we rightshift that by __builtin_ctz(A) + 1, which is q+1:
((~t & -~t) - 1) >> (q + 1)
               =  [..1..]
                    p-1

Which, when |ed with `t+1:
             B = X1[..0..][..1..]
                     q+1    p-1

Which definitely solves the problem, given that we started with:
             A = X0[..1..][..0..]
                      p      q