Set the rightmost unset bit | C ++ implementation to set the rightmost unset bit ; function to find the position of rightmost set bit ; if n = 0 , return 1 ; if all bits of ' n ' are set ; position of rightmost unset bit in ' n ' passing ~ n as argument ; set the bit at position ' pos ' ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPosOfRightmostSetBit ( int n ) { return log2 ( n & - n ) + 1 ; } int setRightmostUnsetBit ( int n ) { if ( n == 0 ) return 1 ; if ( ( n & ( n + 1 ) ) == 0 ) return n ; int pos = getPosOfRightmostSetBit ( ~ n ) ; return ( ( 1 << ( pos - 1 ) ) n ) ; } int main ( ) { int n = 21 ; cout << setRightmostUnsetBit ( n ) ; return 0 ; }