Find the n | Javascript program to find n - th number whose binary representation is palindrome . ; Finds if the kth bit is set in the binary representation ; Returns the position of leftmost set bit in the binary representation ; Finds whether the integer in binary representation is palindrome or not ; One by one compare bits ; Compare left and right bits and converge ; Start from 1 , traverse through all the integers ; If we reach n , break the loop ; Driver code ; Function Call
let INT_MAX = 2147483647 ; function isKthBitSet ( x , k ) { return ( ( x & ( 1 << ( k - 1 ) ) ) > 0 ) ? 1 : 0 ; } function leftmostSetBit ( x ) { let count = 0 ; while ( x > 0 ) { count ++ ; x = x >> 1 ; } return count ; } function isBinPalindrome ( x ) { let l = leftmostSetBit ( x ) ; let r = 1 ; while ( l > r ) { if ( isKthBitSet ( x , l ) != isKthBitSet ( x , r ) ) return 0 ; l -- ; r ++ ; } return 1 ; } function findNthPalindrome ( n ) { let pal_count = 0 ; let i = 0 ; for ( i = 1 ; i <= INT_MAX ; i ++ ) { if ( isBinPalindrome ( i ) > 0 ) { pal_count ++ ; } if ( pal_count == n ) break ; } return i ; } let n = 9 ; document . write ( findNthPalindrome ( n ) ) ;