Next higher number with same number of set bits |  ; this function returns next higher number with same number of set bits as x . ; right most set bit ; reset the pattern and set next higher bit left part of x will be here ; nextHigherOneBit is now part [ D ] of the above explanation . isolate the pattern ; right adjust pattern ; correction factor ; rightOnesPattern is now part [ A ] of the above explanation . integrate new pattern ( Add [ D ] and [ A ] ) ; Driver code
#include <iostream> NEW_LINE using namespace std ; typedef unsigned int uint_t ; uint_t snoob ( uint_t x ) { uint_t rightOne ; uint_t nextHigherOneBit ; uint_t rightOnesPattern ; uint_t next = 0 ; if ( x ) { rightOne = x & - ( signed ) x ; nextHigherOneBit = x + rightOne ; rightOnesPattern = x ^ nextHigherOneBit ; rightOnesPattern = ( rightOnesPattern ) / rightOne ; rightOnesPattern >>= 2 ; next = nextHigherOneBit | rightOnesPattern ; } return next ; } int main ( ) { int x = 156 ; cout << " Next ▁ higher ▁ number ▁ with ▁ same ▁ number ▁ of ▁ set ▁ bits ▁ is ▁ " << snoob ( x ) ; getchar ( ) ; return 0 ; }