Find the n | 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
< ? php function isKthBitSet ( $ x , $ k ) { return ( $ x & ( 1 << ( $ k - 1 ) ) ) ? 1 : 0 ; } function leftmostSetBit ( $ x ) { $ count = 0 ; while ( $ x ) { $ count ++ ; $ x = $ x >> 1 ; } return $ count ; } function isBinPalindrome ( $ x ) { $ l = leftmostSetBit ( $ x ) ; $ r = 1 ; while ( $ l > $ r ) { if ( isKthBitSet ( $ x , $ l ) != isKthBitSet ( $ x , $ r ) ) return 0 ; $ l -- ; $ r ++ ; } return 1 ; } function findNthPalindrome ( $ n ) { $ pal_count = 0 ; $ i = 0 ; for ( $ i = 1 ; $ i <= PHP_INT_MAX ; $ i ++ ) { if ( isBinPalindrome ( $ i ) ) { $ pal_count ++ ; } if ( $ pal_count == $ n ) break ; } return $ i ; } $ n = 9 ; echo ( findNthPalindrome ( $ n ) ) ; ? >