Closest ( or Next ) smaller and greater numbers with same number of set bits | Function to find next smallest number bigger than n ; Compute c0 and c1 ; If there is no bigger number with the same no . of 1 's ; input 1 ; input 2
function getNext ( n ) { let c = n ; let c0 = 0 ; let c1 = 0 ; while ( ( ( c & 1 ) == 0 ) && ( c != 0 ) ) { c0 ++ ; c >>= 1 ; } while ( ( c & 1 ) == 1 ) { c1 ++ ; c >>= 1 ; } if ( c0 + c1 == 31 c0 + c1 == 0 ) return - 1 ; return n + ( 1 << c0 ) + ( 1 << ( c1 - 1 ) ) - 1 ; } let n = 5 ; document . write ( getNext ( n ) + " " ) ; n = 8 ; document . write ( getNext ( n ) ) ;