Find Nth even length palindromic number formed using digits X and Y | C ++ program to find nth even palindromic number of only even length composing of 4 ' s ▁ and ▁ 5' s . ; Utility function to compute n 'th palindrome number ; Calculate the length from above formula as discussed above ; Calculate rank for length L ; Mask to check if i 't bit  is set or not ; If bit is set append '5' else append '4' ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string solve ( int n , char x , char y ) { int length = ceil ( log2 ( n + 2 ) ) - 1 ; int rank = n - ( 1 << length ) + 1 ; string left = " " , right = " " ; for ( int i = length - 1 ; i >= 0 ; i -- ) { int mask = 1 << i ; bool bit = mask & rank ; if ( bit ) { left += y ; right += y ; } else { left += x ; right += x ; } } reverse ( right . begin ( ) , right . end ( ) ) ; return left + right ; } int main ( ) { int n = 23 ; char x = '4' , y = '5' ; string ans = solve ( n , x , y ) ; cout << ans << ' ' ; return 0 ; }