Next greater integer having one more number of set bits | C ++ implementation to find the next greater integer with one more number of set bits ; function to find the position of rightmost set bit . Returns - 1 if there are no set bits ; function to find the next greater integer ; position of rightmost unset bit of n by passing ~ n as argument ; if n consists of unset bits , then set the rightmost unset bit ; n does not consists of unset bits ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstSetBitPos ( int n ) { return ( log2 ( n & - n ) + 1 ) - 1 ; } int nextGreaterWithOneMoreSetBit ( int n ) { int pos = getFirstSetBitPos ( ~ n ) ; if ( pos > -1 ) return ( 1 << pos ) | n ; return ( ( n << 1 ) + 1 ) ; } int main ( ) { int n = 10 ; cout << " Next ▁ greater ▁ integer ▁ = ▁ " << nextGreaterWithOneMoreSetBit ( n ) ; return 0 ; }