text: Smallest number exceeding N whose Kth bit is set | C ++ 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: #include " bits / stdc + + . h " NEW_LINE using namespace std ; int find_next ( int n , int k ) { int ans = 0 ; if ( ( n & ( 1ll << k ) ) == 0 ) { int cur = 0 ; for ( int i = 0 ; i < k ; i ++ ) { if ( n & ( 1ll << i ) ) cur += 1ll << i ; } ans = n - cur + ( 1ll << k ) ; } else { int first_unset_bit = -1 , cur = 0 ; for ( int i = 0 ; i < 64 ; i ++ ) { if ( ( n & ( 1ll << i ) ) == 0 ) { first_unset_bit = i ; break ; } else cur += ( 1ll << i ) ; } ans = n - cur + ( 1ll << first_unset_bit ) ; if ( ( ans & ( 1ll << k ) ) == 0 ) ans += ( 1ll << k ) ; } return ans ; } int main ( ) { int N = 15 , K = 2 ; cout << find_next ( N , K ) ; return 0 ; }