Lucky alive person in a circle | Set | Java 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
import java . io . * ; class GFG { static int luckiest_person ( int n ) { int len = ( int ) ( Math . log ( n ) / Math . log ( 2 ) ) + 1 ; int n2 = n ; for ( int i = 0 ; i < len ; i ++ ) { n2 = n2 ^ ( 1 << i ) ; } return Math . abs ( n - n2 ) ; } public static void main ( String [ ] args ) { int N = 3 ; int lucky_p = luckiest_person ( N ) ; System . out . println ( lucky_p ) ; } }