Position of rightmost set bit | C ++ program for above approach ; Program to find position of rightmost set bit ; Iterate till number > 0 ; Checking if last bit is set ; Increment position and right shift number ; set bit not found . ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int PositionRightmostSetbit ( int n ) { int p = 1 ; while ( n > 0 ) { if ( n & 1 ) { return p ; } p ++ ; n = n >> 1 ; } return -1 ; } int main ( ) { int n = 18 ; int pos = PositionRightmostSetbit ( n ) ; if ( pos != -1 ) cout << pos ; else cout << 0 ; return 0 ; }