Closest ( or Next ) smaller and greater numbers with same number of set bits | Main 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
< ? php function getNext ( $ n ) { $ c = $ n ; $ c0 = 0 ; $ 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 ; } $ n = 5 ; echo getNext ( $ n ) ; $ n = 8 ; echo " STRNEWLINE " ; echo getNext ( $ n ) ; ? >