text: Next greater number than N with exactly one bit different in binary representation of N | CPP program to find next greater number than N with exactly one bit different in binary representation of N ; Function to find next greater number than N with exactly one bit different in binary representation of N ; It is guaranteed that there is a bit zero in the number ; If the shifted bit is zero then break ; increase the bit shift ; increase the power of 2 ; set the lowest bit of the number ; Driver code ; display the next number
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; long long nextGreater ( long long N ) { long long power_of_2 = 1 , shift_count = 0 ; while ( true ) { if ( ( ( N >> shift_count ) & 1 ) % 2 == 0 ) break ; shift_count ++ ; power_of_2 = power_of_2 * 2 ; } return ( N + power_of_2 ) ; } int main ( ) { long long N = 11 ; cout << " The ▁ next ▁ number ▁ is ▁ = ▁ " << nextGreater ( N ) ; return 0 ; }