Find the n | Python 3 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
INT_MAX = 2147483647 NEW_LINE def isKthBitSet ( x , k ) : NEW_LINE INDENT return 1 if ( x & ( 1 << ( k - 1 ) ) ) else 0 NEW_LINE DEDENT def leftmostSetBit ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x ) : NEW_LINE INDENT count += 1 NEW_LINE x = x >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def isBinPalindrome ( x ) : NEW_LINE INDENT l = leftmostSetBit ( x ) NEW_LINE r = 1 NEW_LINE while ( l > r ) : NEW_LINE INDENT if ( isKthBitSet ( x , l ) != isKthBitSet ( x , r ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def findNthPalindrome ( n ) : NEW_LINE INDENT pal_count = 0 NEW_LINE i = 0 NEW_LINE for i in range ( 1 , INT_MAX + 1 ) : NEW_LINE INDENT if ( isBinPalindrome ( i ) ) : NEW_LINE INDENT pal_count += 1 NEW_LINE DEDENT if ( pal_count == n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 9 NEW_LINE print ( findNthPalindrome ( n ) ) NEW_LINE DEDENT