Lucky alive person in a circle | Set | JavaScript 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
function luckiest_person ( n ) { let len = parseInt ( Math . log ( n ) / Math . log ( 2 ) ) + 1 ; let n2 = n ; for ( let i = 0 ; i < len ; i ++ ) { n2 = n2 ^ ( 1 << i ) ; } return Math . abs ( n - n2 ) ; } let N = 3 ; let lucky_p = luckiest_person ( N ) ; document . write ( lucky_p ) ;