Closest ( or Next ) smaller and greater numbers with same number of set bits | Java Implementation of getNext with Same number of bits 1 's is below ; 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 ; Driver Code ; input 1 ; input 2
import java . io . * ; class GFG { static int getNext ( int n ) { int c = n ; int c0 = 0 ; int 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 ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( getNext ( n ) ) ; n = 8 ; System . out . println ( getNext ( n ) ) ; } }