text: Smallest number exceeding N whose Kth bit is set | Java program for the above approach ; Function to find the number greater than n whose Kth bit is set ; Stores the resultant number ; If Kth bit is not set ; cur will be the sum of all powers of 2 < k ; If the current bit is set ; Add Kth power of 2 to n and subtract the all powers of 2 less than K that are set ; If the kth bit is set ; First unset bit position ; sum of bits that are set ; Add Kth power of 2 to n and subtract the all powers of 2 less than K that are set ; If Kth bit became unset then set it again ; Return the resultant number ; Driver Code ; Print ans
code: import java . util . * ; class GFG { static int find_next ( int n , int k ) { int ans = 0 ; if ( ( n & ( 1L << k ) ) == 0 ) { int cur = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( ( n & ( 1L << i ) ) > 0 ) cur += 1L << i ; } ans = ( int ) ( n - cur + ( 1L << k ) ) ; } else { int first_unset_bit = - 1 , cur = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ( n & ( 1L << i ) ) == 0 ) { first_unset_bit = i ; break ; } else cur += ( 1L << i ) ; } ans = ( int ) ( n - cur + ( 1L << first_unset_bit ) ) ; if ( ( ans & ( 1L << k ) ) == 0 ) ans += ( 1L << k ) ; } return ans ; } public static void main ( String [ ] args ) { int N = 15 , K = 2 ; System . out . print ( find_next ( N , K ) ) ; } }