Lucky alive person in a circle | Set | C ++ implementation of the above approach ; to calculate the number of bits in the binary equivalent of n ; Finding complement by inverting the bits one by one from last ; XOR of n2 with ( 1 << i ) to flip the last ( i + 1 ) th bit of binary equivalent of n2 ; n2 will be the one 's complement of n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int luckiest_person ( int n ) { int len = log2 ( n ) + 1 ; int n2 = n ; for ( int i = 0 ; i < len ; i ++ ) { n2 = n2 ^ ( 1 << i ) ; } return abs ( n - n2 ) ; } int main ( ) { int N = 3 ; int lucky_p = luckiest_person ( N ) ; cout << lucky_p ; return 0 ; }