Next higher number with same number of set bits | Java Implementation on above approach ; 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
class GFG { static int snoob ( int x ) { int rightOne , nextHigherOneBit , rightOnesPattern , next = 0 ; if ( x > 0 ) { rightOne = x & - x ; nextHigherOneBit = x + rightOne ; rightOnesPattern = x ^ nextHigherOneBit ; rightOnesPattern = ( rightOnesPattern ) / rightOne ; rightOnesPattern >>= 2 ; next = nextHigherOneBit | rightOnesPattern ; } return next ; } public static void main ( String [ ] args ) { int x = 156 ; System . out . println ( " Next ▁ higher ▁ number ▁ with ▁ same " + " number ▁ of ▁ set ▁ bits ▁ is ▁ " + snoob ( x ) ) ; } }