Nth Binary Palindrome

Last Updated : 11 Apr, 2026

0Find the nth number whose binary representation is a palindrome, ignoring leading zeros, with the sequence starting from 1 (not 0).

Examples:

Input : 1
Output : 1
Explanation: 1st Number whose binary representation
is palindrome is 1 (1)

Input : 9
Output : 27
Explanation: 9th Number whose binary representation
is palindrome is 27 (11011)

[Naive Approach] Iterative Method

Iterate through all integers starting from 1 and examine their binary representation using bit operations. Compare bits from both ends to determine if the number forms a palindrome. Count each valid case and return the number when the count reaches n.

  • Start iterating from i = 1 and check each number one by one.
  • For each number, find its binary length using leftmostSetBit().
  • Compare bits using two pointers (l from left, r from right).
  • Check bits using isKthBitSet() and move inward if equal.
  • If all bits match, increment palindrome count.
  • Stop when count reaches n and return number.
C++
#include <iostream>
#include <climits>
using namespace std;

// Check if k-th bit (1-based) is set
int isKthBitSet(int x, int k) {
    
    return (x & (1 << (k - 1))) ? 1 : 0;
}

// Get number of bits in x
int leftmostSetBit(int x) {
    
    int count = 0;
    while (x) {
        count++;
        x >>= 1;
    }
    return count;
}

// Check if binary form is palindrome
int isBinPalindrome(int x) {
    
    int l = leftmostSetBit(x), r = 1;

    while (l > r) {
        if (isKthBitSet(x, l) != isKthBitSet(x, r))
            return 0;
        l--;
        r++;
    }
    return 1;
}

// Find nth binary palindrome number
int findNthPalindrome(int n) {
    
    int pal_count = 0;
    
    // Traverse through all the integers
    for (int i = 1; i <= INT_MAX; i++) {
        if (isBinPalindrome(i))
            pal_count++;
            
        // Break the loop when count reaches n
        if (pal_count == n)
            return i;
    }
    return -1;
}

int main() {
    int n = 9;
    
    cout << findNthPalindrome(n);
}
C
#include <stdio.h>
#include <limits.h>

// Check if k-th bit (1-based) is set
int isKthBitSet(int x, int k) {
    
    return (x & (1 << (k - 1))) ? 1 : 0;
}

// Get number of bits in x
int leftmostSetBit(int x) {
    
    int count = 0;
    while (x) {
        count++;
        x = x >> 1;
    }
    return count;
}

// Check if binary form is palindrome
int isBinPalindrome(int x) {
    
    int l = leftmostSetBit(x);
    int r = 1;

    // One by one compare bits
    while (l > r) {

        // Compare left and right bits and converge
        if (isKthBitSet(x, l) != isKthBitSet(x, r))
            return 0;
        l--;
        r++;
    }
    return 1;
}

// Find nth binary palindrome number
int findNthPalindrome(int n) {
    
    int pal_count = 0;

    // Traverse through all the integers
    for (int i = 1; i <= INT_MAX; i++) {
        if (isBinPalindrome(i)) {
            pal_count++;
        }
        
        // Break the loop when count reaches n
        if (pal_count == n)
            return i;
    }

    return -1;
}

int main() {
    int n = 9;

    printf("%d", findNthPalindrome(n));
}
Java
import java.io.*;

class GFG {
    static int INT_MAX = 2147483647;

    // Check if k-th bit (1-based) is set
    static int isKthBitSet(int x, int k)
    {
        return ((x & (1 << (k - 1))) > 0) ? 1 : 0;
    }

    // Get number of bits in x
    static int leftmostSetBit(int x)
    {
        int count = 0;
        while (x > 0) {
            count++;
            x = x >> 1;
        }
        return count;
    }

    // Check if binary form is palindrome
    static int isBinPalindrome(int x)
    {
        int l = leftmostSetBit(x);
        int r = 1;

        // One by one compare bits
        while (l > r) {

            // Compare left and right bits and converge
            if (isKthBitSet(x, l) != isKthBitSet(x, r))
                return 0;
            l--;
            r++;
        }
        return 1;
    }

    // Find nth binary palindrome number
    static int findNthPalindrome(int n)
    {
        int pal_count = 0;

        // Traverse through all the integers
        for (int i = 1; i <= INT_MAX; i++) {
            if (isBinPalindrome(i) > 0)
                pal_count++;

            // Break the loop when count reaches n
            if (pal_count == n)
                return i;
        }

        return -1;
    }

    public static void main(String[] args)
    {
        int n = 9;

        System.out.println(findNthPalindrome(n));
    }
}
Python
INT_MAX = 2147483647

# Check if k-th bit (1-based) is set
def isKthBitSet(x, k):
    
    return 1 if (x & (1 << (k - 1))) else 0

# Get number of bits in x
def leftmostSetBit(x):
    
    count = 0
    while x:
        count += 1
        x >>= 1
    return count

# Check if binary form is palindrome
def isBinPalindrome(x):
    
    l = leftmostSetBit(x)
    r = 1

    # One by one compare bits
    while l > r:

        # Compare left and right bits and converge
        if isKthBitSet(x, l) != isKthBitSet(x, r):
            return 0
        l -= 1
        r += 1
    return 1

# Find nth binary palindrome number
def findNthPalindrome(n):
    
    pal_count = 0

    # Traverse through all the integers
    for i in range(1, INT_MAX + 1):
        if isBinPalindrome(i):
            pal_count += 1

        # Break the loop when count reaches n
        if pal_count == n:
            return i

    return -1

if __name__ == "__main__":
    n = 9

    print(findNthPalindrome(n))
C#
using System;

class GFG {

    static int INT_MAX = 2147483647;

    // Check if k-th bit (1-based) is set
    static int isKthBitSet(int x, int k)
    {
        return ((x & (1 << (k - 1))) > 0) ? 1 : 0;
    }

    // Get number of bits in x
    static int leftmostSetBit(int x)
    {
        int count = 0;
        while (x > 0) {
            count++;
            x = x >> 1;
        }
        return count;
    }

    // Check if binary form is palindrome
    static int isBinPalindrome(int x)
    {
        int l = leftmostSetBit(x);
        int r = 1;

        // One by one compare bits
        while (l > r) {

            // Compare left and right bits and converge
            if (isKthBitSet(x, l) != isKthBitSet(x, r))
                return 0;
            l--;
            r++;
        }
        return 1;
    }

    // Find nth binary palindrome number
    static int findNthPalindrome(int n)
    {
        int pal_count = 0;

        // Traverse through all the integers
        for (int i = 1; i <= INT_MAX; i++) {
            if (isBinPalindrome(i) > 0)
                pal_count++;

            // Break the loop when count reaches n
            if (pal_count == n)
                return i;
        }

        return -1;
    }

    static public void Main()
    {
        int n = 9;

        Console.WriteLine(findNthPalindrome(n));
    }
}
JavaScript
let INT_MAX = 2147483647;

// Check if k-th bit (1-based) is set
function isKthBitSet(x, k)
{
    return ((x & (1 << (k - 1))) > 0) ? 1 : 0;
}

// Get number of bits in x
function leftmostSetBit(x)
{
    let count = 0;
    
    while (x > 0)
    {
        count++;
        x = x >> 1;
    }
    return count;
}

// Check if binary form is palindrome
function isBinPalindrome(x)
{
    let l = leftmostSetBit(x);
    let r = 1;

    // One by one compare bits
    while (l > r)
    {
        // Compare left and right bits and converge
        if (isKthBitSet(x, l) != isKthBitSet(x, r))
            return 0;
            
        l--;
        r++;
    }
    return 1;
}

// Find nth binary palindrome number
function findNthPalindrome(n)
{
    let pal_count = 0;

    // Traverse through all the integers
    for (let i = 1; i <= INT_MAX; i++) 
    {
        if (isBinPalindrome(i) > 0)
            pal_count++;

        // Break the loop when count reaches n
        if (pal_count == n)
            return i;
    }
    return -1;
}

// Driver code
let n = 9;

console.log(findNthPalindrome(n));

Output
27


Time complexity: O(x * log x ), Iterate up to the nth palindrome number (x), and each check takes O(log x) time due to bit comparison.

Auxiliary Space: O(1).

[Better Approach] Using BFS - O(n) Time and O(n) Space

Use BFS (queue) to generate binary palindromes level by level starting from "11". At each step, expand the current string by inserting bits at the middle to form new palindromes. Continue this level-wise generation until the nth palindrome is reached and return its integer value.

  • Initialize queue with "11".
  • Pop string, decrement n, and process it.
  • If n == 0, return current string converted to integer.
  • If even length, insert "0" and "1" at middle and push.
  • If odd length, duplicate middle character and push.
  • Repeat until nth palindrome is reached.
11
C++
#include <iostream>
#include <queue>
#include <string>
using namespace std;

// Convert binary string into integer
int convertStringToInt(string s)
{
    int num = 0;

    for (int i = 0; i < s.size(); i++)
        num = num * 2 + (s[i] - '0');

    return num;
}

// Find nth binary palindrome number
int getNthNumber(int n)
{
    // Base case
    if (n == 1)
        return 1;

    n--;

    // Store binary palindrome strings
    queue<string> q;

    // Initialize with second palindrome
    q.push("11");

    // Generate palindromes using BFS
    while (!q.empty()) {

        string curr = q.front();
        q.pop();
        n--;

        // Return when nth palindrome is reached
        if (!n)
            return convertStringToInt(curr);

        int mid = curr.size() / 2;

        // If length is even, insert 0 and 1 at middle
        if (curr.size() % 2 == 0) {
            string s0 = curr, s1 = curr;
            s0.insert(mid, "0");
            s1.insert(mid, "1");
            q.push(s0);
            q.push(s1);
        }
        
        // If length is odd, duplicate middle character
        else {
            string temp = curr;
            temp.insert(mid, string(1, curr[mid]));
            q.push(temp);
        }
    }

    return 0;
}

int main()
{
    int n = 9;

    cout << getNthNumber(n);
}
Java
import java.io.*;
import java.util.*;

class GFG {

    // Convert binary string into integer
    public static int convertStringToInt(String s)
    {
        int num = 0;

        for (int i = 0; i < s.length(); i++)
            num = num * 2 + (s.charAt(i) - '0');

        return num;
    }

    // Find nth binary palindrome number
    public static int getNthNumber(int n)
    {
        // Base case
        if (n == 1)
            return 1;

        n--;

        // Store binary palindrome strings
        Queue<String> q = new LinkedList<>();

        // Initialize with second palindrome
        q.add("11");

        // Generate palindromes using BFS
        while (!q.isEmpty()) {

            String curr = q.poll();
            n--;

            // Return when nth palindrome is reached
            if (n == 0)
                return convertStringToInt(curr);

            int mid = curr.length() / 2;

            // If length is even, insert 0 and 1 at middle
            if (curr.length() % 2 == 0) {
                q.add(curr.substring(0, mid) + "0" + curr.substring(mid));
                q.add(curr.substring(0, mid) + "1" + curr.substring(mid));
            }
            
            // If length is odd, duplicate middle character
            else {
                char midChar = curr.charAt(mid);
                q.add(curr.substring(0, mid) + midChar + curr.substring(mid));
            }
        }

        return -1;
    }

    public static void main(String[] args)
    {
        int n = 9;

        System.out.println(getNthNumber(n));
    }
}
Python
# Convert binary string into integer
def convertStringToInt(s):
    
    num = 0

    for i in range(len(s)):
        num = num * 2 + (ord(s[i]) - ord('0'))

    return num

# Find nth binary palindrome number
def getNthNumber(n):

    # Base case
    if n == 1:
        return 1

    n -= 1

    # Store binary palindrome strings
    q = []

    # Initialize with second palindrome
    q.append("11")

    # Generate palindromes using BFS
    while len(q) != 0:

        curr = q.pop(0)
        n -= 1

        # Return when nth palindrome is reached
        if n == 0:
            return convertStringToInt(curr)

        mid = len(curr) // 2

        # If length is even, insert 0 and 1 at middle
        if len(curr) % 2 == 0:
            q.append(curr[:mid] + "0" + curr[mid:])
            q.append(curr[:mid] + "1" + curr[mid:])
        
        # If length is odd, duplicate middle character
        else:
            q.append(curr[:mid] + curr[mid] + curr[mid:])

    return 0

if __name__ == "__main__":
    n = 9

    print(getNthNumber(n))
C#
using System;
using System.Collections.Generic;

class GFG{

// Convert binary string into integer
public static int convertStringToInt(String s)
{
    int num = 0;

    for(int i = 0; i < s.Length; i++) 
        num = num * 2 + (s[i] - '0');

    return num;
}

// Find nth binary palindrome number
public static int getNthNumber(int n)
{
    // Base case
    if (n == 1)
        return 1;
        
    n--;

    // Store binary palindrome strings
    Queue<String> q = new Queue<String>();

    // Initialize with second palindrome
    q.Enqueue("11");

    // Generate palindromes using BFS
    while (q.Count > 0) 
    {
        String curr = q.Dequeue();
        n--;

        // Return when nth palindrome is reached
        if (n == 0)
            return convertStringToInt(curr);

        int mid = curr.Length / 2;

        // If length is even, insert 0 and 1 at middle
        if (curr.Length % 2 == 0)
        {
            q.Enqueue(curr.Substring(0, mid) + "0" + curr.Substring(mid));
            q.Enqueue(curr.Substring(0, mid) + "1" + curr.Substring(mid));
        }

        // If length is odd, duplicate middle character
        else 
        {
            q.Enqueue(curr.Substring(0, mid) + curr[mid] + curr.Substring(mid));
        }
    }
    return -1;
}

public static void Main(String[] args)
{
    int n = 9;
  
    Console.WriteLine(getNthNumber(n));
}
}
JavaScript
// Convert binary string into integer
function convertStringToInt(s)
{
    let num = 0;

    for (let i = 0; i < s.length; i++)
        num = num * 2 + (s[i] - '0');

    return num;
}

// Find nth binary palindrome number
function getNthNumber(n)
{
    // Base case
    if (n == 1)
        return 1;

    n--;

    // Store binary palindrome strings
    let q = [];

    // Initialize with second palindrome
    q.push("11");

    // Generate palindromes using BFS
    while (q.length > 0) {

        let curr = q.shift();
        n--;

        // Return when nth palindrome is reached
        if (n == 0)
            return convertStringToInt(curr);

        let mid = Math.floor(curr.length / 2);

        // If length is even, insert 0 and 1 at middle
        if (curr.length % 2 == 0) {
            q.push(curr.substring(0, mid) + "0" + curr.substring(mid));
            q.push(curr.substring(0, mid) + "1" + curr.substring(mid));
        }
        
        // If length is odd, duplicate middle character
        else {
            q.push(curr.substring(0, mid) + curr[mid] + curr.substring(mid));
        }
    }

    return -1;
}

// Driver code
let n = 9;

console.log(getNthNumber(n));

Output
27

[Expected Approach] Constructing the nth palindrome - O(1) Time and O(1) Space

If we observe the first few binary palindromes it can be divided into groups based on their length:

  • Group 0: 1
  • Group 1: 11, 101, 111
  • Group 2: 1001, 1111, 10001, 10101, 11011, 11111
  • Group 3: 100001, 101101, 110011, 111111, ...

Group 1 is formed by taking two 1s at the corner and filling 0 or 1 bits in between
Group 2 is formed by taking two 1s at the corner and filling 2 or 3 bits in between
Group 3 is formed by taking two 1s at the corner and filling 4 or 5 bits in between

The number of palindromes in a group is given by 3 * 2^(groupNo - 1) for groupNo >= 1, and for groupNo = 0, there is only 1 palindrome.

Now, directly construct the nth binary palindrome using group and offset. Use symmetry to fix outer bits and determine middle and inner bits.

Let us construct the 8th binary palindrome number
The group number will be 2, and no.of elements before that group are 1 + 3 * 2^1 which is 4

So the offset for the 8th element will be 8 - 4 - 1 = 3

And first 2^(groupno - 1) = 2^1, elements will have even length(in binary representation) of 2*groupno, next 2^groupno elements will have odd
length(in binary representation) of 2*groupno + 1

Place bit 1 as the first bit and as the last bit (firstbit: 0, last bit: 2*groupno or 2*groupno - 1)

As the offset is 3, 4th(3 + 1) element in the group, will have odd length and have 1 in the middle

Below is the table of middle bit to be used for the given offset for the group 2

offset    middle bit
0 |
1 |
2 0
3 1
4 0
5 1

And we should be filling the binary representation of number 0(((groupoffset) - 2^(groupno-1)) /2) from middle n both directions 1 0 1 0 1

FirstElement Number MiddleElement Number LastElement
1 0 1 0 1

The 8th number will be 21

C++
#include <iostream>
using namespace std;

// Construct the nth binary palindrome using
// group number, auxiliary number and operation type
int constructNthNumber(int group_no, int aux_num, int op)
{
    int INT_SIZE = 32;
    int a[INT_SIZE] = {0};
    int num = 0, len_f;
    int i = 0;
    
    // No middle bit
    if (op == 2) 
    {
        // Final length
        len_f = 2 * group_no;

        // Set first and last bit
        a[len_f - 1] = a[0] = 1;

        // Fill bits symmetrically from middle
        while (aux_num) 
        {
            a[group_no + i] = a[group_no - 1 - i] = aux_num & 1;
            aux_num >>= 1;
            i++;
        }
    }

    // Insert 0 in middle
    else if (op == 0)
    {
        // Final length
        len_f = 2 * group_no + 1;

        // Set first, last and middle bit
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 0;

        // Fill remaining bits symmetrically
        while (aux_num)
        {
            a[group_no + 1 + i] = a[group_no - 1 - i] = aux_num & 1;
            aux_num >>= 1;
            i++;
        }
    }
    
    // Insert 1 in middle
    else 
    {
        // Final length
        len_f = 2 * group_no + 1;

        // Set first, last and middle bit
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 1;

        // Fill remaining bits symmetrically
        while (aux_num) 
        {
            a[group_no + 1 + i] = a[group_no - 1 - i] = aux_num & 1;
            aux_num >>= 1;
            i++;
        }
    }

    // Convert binary array to decimal
    for (i = 0; i < len_f; i++)
        num += (1 << i) * a[i];
        
    return num;
}

// Find nth binary palindrome number
int getNthNumber(int n)
{
    int group_no = 0, group_offset;
    int count_upto_group = 0, count_temp = 1;
    int op, aux_num;

    // Find the group where nth element lies
    while (count_temp < n)
    {
        group_no++;
        count_upto_group = count_temp;
        count_temp += 3 * (1 << (group_no - 1));
    }

    // Offset inside the group
    group_offset = n - count_upto_group - 1;

    // Decide middle bit and auxiliary number
    if ((group_offset + 1) <= (1 << (group_no - 1)))
    {
        op = 2; 
        aux_num = group_offset;
    }
    else
    {
        if (((group_offset + 1) - (1 << (group_no - 1))) % 2)
            op = 0; 
        else
            op = 1;

        aux_num = (group_offset - (1 << (group_no - 1))) / 2;
    }

    return constructNthNumber(group_no, aux_num, op);
}

int main()
{
    int n = 9;

    cout << getNthNumber(n);
}
C
#include <stdio.h>
#define INT_SIZE 32

// Construct the nth binary palindrome using
// group number, auxiliary number and operation type
int constructNthNumber(int group_no, int aux_num, int op)
{
    int a[INT_SIZE] = {0};

    int num = 0, len_f;
    int i = 0;

    // No middle bit
    if (op == 2) 
    {
        // Final length
        len_f = 2 * group_no;

        // Set first and last bit
        a[len_f - 1] = a[0] = 1;

        // Fill bits symmetrically from middle
        while (aux_num) 
        {
            a[group_no + i] = a[group_no - 1 - i] = aux_num & 1;
            aux_num >>= 1;
            i++;
        }
    }

    // Insert 0 in middle
    else if (op == 0) 
    {
        // Final length
        len_f = 2 * group_no + 1;

        // Set first, last and middle bit
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 0;

        // Fill remaining bits symmetrically
        while (aux_num) 
        {
            a[group_no + 1 + i] = a[group_no - 1 - i] = aux_num & 1;
            aux_num >>= 1;
            i++;
        }
    }
    
    // Insert 1 in middle
    else 
    {
        // Final length
        len_f = 2 * group_no + 1;

        // Set first, last and middle bit
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 1;

        // Fill remaining bits symmetrically
        while (aux_num) 
        {
            a[group_no + 1 + i] = a[group_no - 1 - i] = aux_num & 1;
            aux_num >>= 1;
            i++;
        }
    }

    // Convert binary array to decimal
    for (i = 0; i < len_f; i++)
        num += (1 << i) * a[i];

    return num;
}

// Find nth binary palindrome number
int getNthNumber(int n)
{
    int group_no = 0, group_offset;
    int count_upto_group = 0, count_temp = 1;
    int op, aux_num;

    // Find the group where nth element lies
    while (count_temp < n) 
    {
        group_no++;

        count_upto_group = count_temp;
        count_temp += 3 * (1 << (group_no - 1));
    }

    // Offset inside the group
    group_offset = n - count_upto_group - 1;

    // Decide middle bit and auxiliary number
    if ((group_offset + 1) <= (1 << (group_no - 1))) 
    {
        op = 2; 
        aux_num = group_offset;
    }
    else 
    {
        if (((group_offset + 1) - (1 << (group_no - 1))) % 2)
            op = 0; 
        else
            op = 1;

        aux_num = (group_offset - (1 << (group_no - 1))) / 2;
    }

    return constructNthNumber(group_no, aux_num, op);
}

int main()
{
    int n = 9;

    printf("%d", getNthNumber(n));
    return 0;
}
Java
class GFG {

    static int INT_SIZE = 32;

    // Construct the nth binary palindrome using
    // group number, auxiliary number and operation type
    static int constructNthNumber(int group_no, int aux_num,
                                  int op)
    {
        int a[] = new int[INT_SIZE];

        int num = 0, len_f;
        int i = 0;

        // No middle bit
        if (op == 2) {
            
            // Final length
            len_f = 2 * group_no;

            // Set first and last bit
            a[len_f - 1] = a[0] = 1;

            // Fill bits symmetrically from middle
            while (aux_num > 0) {
                a[group_no + i] 
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }

        // Insert 0 in middle
        else if (op == 0) {
            
            // Final length
            len_f = 2 * group_no + 1;

            // Set first, last and middle bit
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 0;

            // Fill remaining bits symmetrically
            while (aux_num > 0) {
                a[group_no + 1 + i] 
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
        
        // Insert 1 in middle
        else 
        {
            // Final length
            len_f = 2 * group_no + 1;

            // Set first, last and middle bit
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 1;

            // Fill remaining bits symmetrically
            while (aux_num > 0) {
                a[group_no + 1 + i] 
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }

        // Convert binary array to decimal
        for (i = 0; i < len_f; i++)
            num += (1 << i) * a[i];
        return num;
    }

    // Find nth binary palindrome number
    static int getNthNumber(int n)
    {
        int group_no = 0, group_offset;
        int count_upto_group = 0, count_temp = 1;
        int op, aux_num;

        // Find the group where nth element lies
        while (count_temp < n) {
            group_no++;

            count_upto_group = count_temp;
            count_temp += 3 * (1 << (group_no - 1));
        }

        // Offset inside the group
        group_offset = n - count_upto_group - 1;

        // Decide middle bit and auxiliary number
        if ((group_offset + 1) <= (1 << (group_no - 1))) {
            op = 2;

            aux_num = group_offset;
        }
        else {
            if (((group_offset + 1) 
                 - (1 << (group_no - 1))) % 2 == 1)
                op = 0;
            else
                op = 1;

            aux_num
                = (group_offset 
                - (1 << (group_no - 1))) / 2;
        }

        return constructNthNumber(group_no, aux_num, op);
    }

    public static void main(String[] args)
    {
        int n = 9;
      
        System.out.printf("%d", getNthNumber(n));
    }
}
Python
INT_SIZE = 32

# Construct the nth binary palindrome using
# group number, auxiliary number and operation type
def constructNthNumber(group_no, aux_num, op):

    a = [0] * INT_SIZE
    num, i = 0, 0

    # No middle bit
    if op == 2:

        # Final length
        len_f = 2 * group_no

        # Set first and last bit
        a[len_f - 1] = a[0] = 1

        # Fill bits symmetrically from middle
        while aux_num:
            a[group_no + i] = a[group_no - 1 - i] = aux_num & 1
            aux_num >>= 1
            i += 1

    # Insert 0 in middle
    elif op == 0:

        # Final length
        len_f = 2 * group_no + 1

        # Set first, last and middle bit
        a[len_f - 1] = a[0] = 1
        a[group_no] = 0

        # Fill remaining bits symmetrically
        while aux_num:
            a[group_no + 1 + i] = a[group_no - 1 - i] = aux_num & 1
            aux_num >>= 1
            i += 1

    # Insert 1 in middle
    else:

        # Final length
        len_f = 2 * group_no + 1

        # Set first, last and middle bit
        a[len_f - 1] = a[0] = 1
        a[group_no] = 1

        # Fill remaining bits symmetrically
        while aux_num:
            a[group_no + 1 + i] = a[group_no - 1 - i] = aux_num & 1
            aux_num >>= 1
            i += 1

    # Convert binary array to decimal
    for i in range(len_f):
        num += (1 << i) * a[i]
    return num


# Find nth binary palindrome number
def getNthNumber(n):

    group_no = 0
    count_upto_group, count_temp = 0, 1

    # Find the group where nth element lies
    while count_temp < n:

        group_no += 1
        count_upto_group = count_temp
        count_temp += 3 * (1 << (group_no - 1))

    # Offset inside the group
    group_offset = n - count_upto_group - 1

    # Decide middle bit and auxiliary number
    if (group_offset + 1) <= (1 << (group_no - 1)):

        op = 2
        aux_num = group_offset

    else:

        if ((group_offset + 1 - (1 << (group_no - 1))) % 2):
            op = 0
        else:
            op = 1

        aux_num = (group_offset - (1 << (group_no - 1))) // 2

    return constructNthNumber(group_no, aux_num, op)


if __name__ == "__main__":

    n = 9

    print(getNthNumber(n))
C#
using System;

class GFG {

    static int INT_SIZE = 32;

    // Construct the nth binary palindrome using
    // group number, auxiliary number and operation type
    static int constructNthNumber(int group_no, int aux_num,
                                  int op)
    {
        int[] a = new int[INT_SIZE];

        int num = 0, len_f;
        int i = 0;

        // No middle bit
        if (op == 2) {
           
            // Final length
            len_f = 2 * group_no;

            // Set first and last bit
            a[len_f - 1] = a[0] = 1;

            // Fill bits symmetrically from middle
            while (aux_num > 0) {
                a[group_no + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }

        // Insert 0 in middle
        else if (op == 0) {
           
            // Final length
            len_f = 2 * group_no + 1;

            // Set first, last and middle bit
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 0;

            // Fill remaining bits symmetrically
            while (aux_num > 0) {
                a[group_no + 1 + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
        
        // Insert 1 in middle
        else 
        {
            // Final length
            len_f = 2 * group_no + 1;

            // Set first, last and middle bit
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 1;

            // Fill remaining bits symmetrically
            while (aux_num > 0) {
                a[group_no + 1 + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }

        // Convert binary array to decimal
        for (i = 0; i < len_f; i++)
            num += (1 << i) * a[i];
        return num;
    }

    // Find nth binary palindrome number 
    static int getNthNumber(int n)
    {
        int group_no = 0, group_offset;
        int count_upto_group = 0, count_temp = 1;
        int op, aux_num;

        // Find the group where nth element lies
        while (count_temp < n) {
            group_no++;

            count_upto_group = count_temp;
            count_temp += 3 * (1 << (group_no - 1));
        }

        // Offset inside the group
        group_offset = n - count_upto_group - 1;

        // Decide middle bit and auxiliary number 
        if ((group_offset + 1) <= (1 << (group_no - 1))) {
            op = 2;

            aux_num = group_offset;
        }
        else {
            if (((group_offset + 1) - (1 << (group_no - 1)))
                    % 2
                == 1)
                op = 0;
            else
                op = 1;

            aux_num
                = (group_offset - (1 << (group_no - 1)))
                  / 2;
        }

        return constructNthNumber(group_no, aux_num, op);
    }

    public static void Main(String[] args)
    {
        int n = 9;
      
        Console.Write("{0}", getNthNumber(n));
    }
}
JavaScript
var INT_SIZE = 32;

// Construct the nth binary palindrome using
// group number, auxiliary number and operation type
function constructNthNumber(group_no , aux_num,op)
{
    var a = Array.from({length: INT_SIZE}, () => 0);

    var num = 0, len_f=0;
    var i = 0;

    // No middle bit
    if (op == 2) 
    {
        
        // Final length
        len_f = 2 * group_no;

        // Set first and last bit
        a[len_f - 1] = a[0] = 1;

        // Fill bits symmetrically from middle
        while (aux_num > 0) 
        {
            a[group_no + i] 
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }

    // Insert 0 in middle
    else if (op == 0) 
    {
        
        // Final length
        len_f = 2 * group_no + 1;

        // Set first, last and middle bit
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 0;

        // Fill remaining bits symmetrically
        while (aux_num > 0) 
        {
            a[group_no + 1 + i] 
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
    
    // Insert 1 in middle
    else 
    {
        
        // Final length
        len_f = 2 * group_no + 1;

        // Set first, last and middle bit
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 1;

        // Fill remaining bits symmetrically
        while (aux_num > 0)
        {
            a[group_no + 1 + i] 
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }

    // Convert binary array to decimal 
    for(i = 0; i < len_f; i++)
        num += (1 << i) * a[i];
        
    return num;
}

// Find nth binary palindrome number
function getNthNumber(n)
{
    var group_no = 0, group_offset;
    var count_upto_group = 0, count_temp = 1;
    var op, aux_num;

    // Find the group where nth element lies
    while (count_temp < n) 
    {
        group_no++;

        count_upto_group = count_temp;
        count_temp += 3 * (1 << (group_no - 1));
    }

    // Offset inside the group
    group_offset = n - count_upto_group - 1;

    // Decide middle bit and auxiliary number
    if ((group_offset + 1) <= (1 << (group_no - 1)))
    {
        op = 2; 

        aux_num = group_offset;
    }
    else
    {
        if (((group_offset + 1) - 
           (1 << (group_no - 1))) % 2 == 1)
            op = 0; 
        else
            op = 1; 

        aux_num = ((group_offset) -  
             (1 << (group_no - 1))) / 2;
    }
    return constructNthNumber(group_no, aux_num, op);
}

// Driver code
var n = 9;

console.log(getNthNumber(n));

Output
27
Comment