📜  查找其二进制表示为回文的第n个数字

📅  最后修改于: 2021-04-29 12:28:33             🧑  作者: Mango

找出第n个数字,其二进制表示形式是回文。在考虑二进制表示时,请不要考虑前导零。将二进制表示为回文的第一个数字视为1,而不是0

例子:

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

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

方法1:天真
如果数字是回文,那么幼稚的方法是遍历所有从1到2 ^ 31 – 1的整数并增加回文数。当回文数达到所需的n时,中断循环并返回当前整数。

C++
// C++ program to find n-th number whose binary
// representation is palindrome.
#include 
using namespace std;
 
// Finds if the kth bit is set in the binary
// representation
int isKthBitSet(int x, int k)
{
    return (x & (1 << (k - 1))) ? 1 : 0;
}
 
// Returns the position of leftmost set bit
// in the binary representation
int leftmostSetBit(int x)
{
    int count = 0;
    while (x) {
        count++;
        x = x >> 1;
    }
    return count;
}
 
// Finds whether the integer in binary
// representation is palindrome or not
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;
}
 
int findNthPalindrome(int n)
{
    int pal_count = 0;
 
    // Start from 1, traverse through
    // all the integers
    int i = 0;
    for (i = 1; i <= INT_MAX; i++) {
        if (isBinPalindrome(i)) {
            pal_count++;
        }
        // If we reach n, break the loop
        if (pal_count == n)
            break;
    }
 
    return i;
}
 
// Driver code
int main()
{
    int n = 9;
   
    // Function Call
    cout << findNthPalindrome(n);
}
 
// This code is contributed
// by Akanksha Rai


C
// C program to find n-th number whose binary
// representation is palindrome.
#include 
#define INT_MAX 2147483647
 
// Finds if the kth bit is set in the binary
// representation
int isKthBitSet(int x, int k)
{
    return (x & (1 << (k - 1))) ? 1 : 0;
}
 
// Returns the position of leftmost set bit
// in the binary representation
int leftmostSetBit(int x)
{
    int count = 0;
    while (x) {
        count++;
        x = x >> 1;
    }
    return count;
}
 
// Finds whether the integer in binary
// representation is palindrome or not
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;
}
 
int findNthPalindrome(int n)
{
    int pal_count = 0;
 
    // Start from 1, traverse through
    // all the integers
    int i = 0;
    for (i = 1; i <= INT_MAX; i++) {
        if (isBinPalindrome(i)) {
            pal_count++;
        }
        // If we reach n, break the loop
        if (pal_count == n)
            break;
    }
 
    return i;
}
 
// Driver code
int main()
{
    int n = 9;
   
    // Function Call
    printf("%d", findNthPalindrome(n));
}


Java
// Java program to find n-th
// number whose binary
// representation is palindrome.
import java.io.*;
 
class GFG {
    static int INT_MAX = 2147483647;
 
    // Finds if the kth bit
    // is set in the binary
    // representation
    static int isKthBitSet(int x, int k)
    {
        return ((x & (1 << (k - 1))) > 0) ? 1 : 0;
    }
 
    // Returns the position of
    // leftmost set bit in the
    // binary representation
    static int leftmostSetBit(int x)
    {
        int count = 0;
        while (x > 0) {
            count++;
            x = x >> 1;
        }
        return count;
    }
 
    // Finds whether the integer
    // in binary representation is
    // palindrome or not
    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;
    }
 
    static int findNthPalindrome(int n)
    {
        int pal_count = 0;
 
        // Start from 1, traverse
        // through all the integers
        int i = 0;
        for (i = 1; i <= INT_MAX; i++) {
            if (isBinPalindrome(i) > 0) {
                pal_count++;
            }
 
            // If we reach n,
            // break the loop
            if (pal_count == n)
                break;
        }
 
        return i;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 9;
       
        // Function Call
        System.out.println(findNthPalindrome(n));
    }
}
 
// This code is contributed
// by anuj_67.


Python 3
# Python 3 program to find n-th number
# whose binary representation is palindrome.
INT_MAX = 2147483647
 
# Finds if the kth bit is set in
# the binary representation
 
 
def isKthBitSet(x, k):
 
    return 1 if (x & (1 << (k - 1))) else 0
 
# Returns the position of leftmost
# set bit in the binary representation
 
 
def leftmostSetBit(x):
 
    count = 0
    while (x):
        count += 1
        x = x >> 1
 
    return count
 
# Finds whether the integer in binary
# representation is palindrome or not
 
 
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
 
 
def findNthPalindrome(n):
    pal_count = 0
 
    # Start from 1, traverse
    # through all the integers
    i = 0
    for i in range(1, INT_MAX + 1):
        if (isBinPalindrome(i)):
            pal_count += 1
 
        # If we reach n, break the loop
        if (pal_count == n):
            break
 
    return i
 
 
# Driver code
if __name__ == "__main__":
    n = 9
     
    # Function Call
    print(findNthPalindrome(n))
 
# This code is contributed
# by ChitraNayal


C#
// C# program to find n-th
// number whose binary
// representation is palindrome.
using System;
 
class GFG {
 
    static int INT_MAX = 2147483647;
 
    // Finds if the kth bit
    //  is set in the binary
    // representation
    static int isKthBitSet(int x, int k)
    {
        return ((x & (1 << (k - 1))) > 0) ? 1 : 0;
    }
 
    // Returns the position of
    // leftmost set bit in the
    // binary representation
    static int leftmostSetBit(int x)
    {
        int count = 0;
        while (x > 0) {
            count++;
            x = x >> 1;
        }
        return count;
    }
 
    // Finds whether the integer
    // in binary representation is
    // palindrome or not
    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;
    }
 
    static int findNthPalindrome(int n)
    {
        int pal_count = 0;
 
        // Start from 1, traverse
        // through all the integers
        int i = 0;
        for (i = 1; i <= INT_MAX; i++) {
            if (isBinPalindrome(i) > 0) {
                pal_count++;
            }
 
            // If we reach n,
            // break the loop
            if (pal_count == n)
                break;
        }
 
        return i;
    }
 
    // Driver code
    static public void Main()
    {
        int n = 9;
       
        // Function Call
        Console.WriteLine(findNthPalindrome(n));
    }
}
 
// This code is contributed ajit


PHP
> 1;
    }
    return $count;
}
 
// Finds whether the integer in binary
// representation is palindrome or not
function 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--;
        $r++;
    }
    return 1;
}
 
function findNthPalindrome($n)
{
    $pal_count = 0;
 
    // Start from 1, traverse through
    // all the integers
    $i = 0;
    for ($i = 1; $i <= PHP_INT_MAX; $i++)
    {
        if (isBinPalindrome($i))
        {
            $pal_count++;
        }
         
        // If we reach n, break the loop
        if ($pal_count == $n)
            break;
    }
    return $i;
}
 
// Driver code
$n = 9;
 
// Function Call
echo (findNthPalindrome($n));
 
// This code is contributed by jit_t
?>


C++
// C++ program to find n-th palindrome
#include 
using namespace std;
 
// utility function which is used to
// convert binary string into integer
int convertStringToInt(string s)
{
    int num = 0;
 
    // convert binary string into integer
    for (int i = 0; i < s.size(); i++) {
        num = num * 2 + (s[i] - '0');
    }
    return num;
}
 
// function to find nth binary palindrome number
int getNthNumber(int n)
{
 
    // base case
    if (n == 1)
        return 1;
    n--;
 
    // stores the binary palindrome string
    queue q;
 
    // add 2nd binary palindrome string
    q.push("11");
 
    // runs till the nth binary palindrome number
    while (!q.empty()) {
        // remove curr binary palindrome string from queue
        string curr = q.front();
        q.pop();
        n--;
 
        // if n==0 then we find the n'th binary palindrome
        // so we return our answer
        if (!n) {
            return convertStringToInt(curr);
        }
 
        int mid = curr.size() / 2;
 
        // if length is even .so it is our first case
        // we have two choices
        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 .so it is our second case
        // we have only one choice
        else {
            string ch(1, curr[mid]);
            string temp = curr;
            temp.insert(mid, ch);
            q.push(temp);
        }
    }
 
    return 0;
}
 
// Driver Code
int main()
{
    int n = 9;
     
    // Function Call
    cout << getNthNumber(n);
}
 
// This code is contributed by Sagar Jangra and Naresh
// Saharan


Java
// Java program to find n-th palindrome
import java.io.*;
import java.util.*;
class GFG {
 
    // utility function which is used to
    // convert binary string into integer
    public static int convertStringToInt(String s)
    {
        int ans = 0;
 
        // convert binary string into integer
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1')
                ans += 1 << i;
        }
        return ans;
    }
 
    // function to find nth binary palindrome number
    public static int getNthNumber(int n)
    {
        // stores the binary palindrome string
        Queue q = new LinkedList<>();
 
        // base case
        if (n == 1)
            return 1;
        n = n - 1;
 
        // add 2nd binary palindrome string
        q.add("11");
 
        // runs till the nth binary palindrome number
        while (n-- > 0) {
 
            // remove curr binary palindrome string from
            // queue
            String curr = q.remove();
 
            // if n==0 then we find the n'th binary
            // palindrome so we return our answer
            if (n == 0)
                return convertStringToInt(curr);
 
            // calculate length of curr binary palindrome
            // string
            int len = curr.length();
 
            // if length is even .so it is our first case
            // we have two choices
            if (len % 2 == 0) {
                q.add(curr.substring(0, len / 2) + "0"
                      + curr.substring(len / 2));
                q.add(curr.substring(0, len / 2) + "1"
                      + curr.substring(len / 2));
            }
 
            // if length is odd .so it is our second case
            // we have only one choice
            else {
                char midChar = curr.charAt(len / 2);
                q.add(curr.substring(0, len / 2) + midChar
                      + curr.substring(len / 2));
            }
        }
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 9;
       
        // Function Call
        System.out.println(getNthNumber(n));
    }
}
// This code is contributed by Naresh Saharan and Sagar
// Jangra


Python3
# Python program to find n-th palindrome
 
# utility function which is used to
# convert binary string into integer
def convertStringToInt(s):
    ans = 0
     
    # convert binary string into integer
    for i in range(len(s)):
        ans = ans * 2 + (ord(s[i]) - ord('0'))
     
    return ans
 
# function to find nth binary palindrome number
def getNthNumber(n):
     
    # stores the binary palindrome string
    q = []
     
    # base case
    if(n == 1):
        return 1
    n = n - 1
     
    # add 2nd binary palindrome string
    q.append("11")
     
    # runs till the nth binary palindrome number
    while(len(q) != 0):
         
        # remove curr binary palindrome string from
        # queue
        curr = q.pop(0)
        n -= 1
         
        # if n==0 then we find the n'th binary
        # palindrome so we return our answer
        if(n ==0):
            return convertStringToInt(curr)
         
        # calculate length of curr binary palindrome
        # string
        lenn = len(curr)
         
        # if length is even .so it is our first case
        # we have two choices
        if (len(curr) % 2 == 0):
            q.append(curr[0:int(lenn/2)]+"0"+curr[int(lenn/2):])
            q.append(curr[0:int(lenn/2)]+"1"+curr[int(lenn/2):])
         
        # if length is odd .so it is our second case
        # we have only one choice
        else:
            midChar = curr[int(lenn/2)]
            q.append(curr[0:int(lenn/2)]+midChar+curr[int(lenn/2):])
         
    return 0
             
# Driver code
n = 9
 
# Function Call
print(getNthNumber(n))
 
# This code is contributed by avanitrachhadiya2155


C
// Efficient C program to find n-th palindrome
#include 
#define INT_SIZE 32
 
// Construct the nth binary palindrome with the
// given group number, aux_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 need to insert any bit in the middle
    if (op == 2) {
         
        // Length of the final binary representation
        len_f = 2 * group_no;
 
        // Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1;
 
        // Start filling the a[] from middle,
        // with the aux_num binary representation
        while (aux_num) {
             
            // Get the auxiliary number's ith bit and
            // fill around middle
            a[group_no + i]
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
 
    // Insert bit 0 in the middle
    else if (op == 0) {
         
        // Length of the final binary representation
        len_f = 2 * group_no + 1;
 
        // Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 0;
 
        // Start filling the a[] from middle, with
        // the aux_num binary representation
        while (aux_num) {
            // Get the auxiliary number's ith bit and fill
            // around middle
            a[group_no + 1 + i]
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
    else // Insert bit 1 in the middle
    {
        // Length of the final binary representation
        len_f = 2 * group_no + 1;
 
        // Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 1;
 
        // Start filling the a[] from middle, with
        // the aux_num binary representation
        while (aux_num) {
             
            // Get the auxiliary number's ith bit and fill
            // around middle
            a[group_no + 1 + i]
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
 
    // Convert the number to decimal from binary
    for (i = 0; i < len_f; i++)
        num += (1 << i) * a[i];
    return num;
}
 
// Will return the 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;
 
    // Add number of elements in all the groups,
    // until the group of the nth number is found
    while (count_temp < n) {
        group_no++;
 
        // Total number of elements until this group
        count_upto_group = count_temp;
        count_temp += 3 * (1 << (group_no - 1));
    }
 
    // Element's offset position in the group
    group_offset = n - count_upto_group - 1;
 
    // Finding which bit to be placed in the
    // middle and finding the number, which we
    // will fill from the middle in both
    // directions
    if ((group_offset + 1) <= (1 << (group_no - 1))) {
        op = 2; // No need to put extra bit in middle
 
        // We need to fill this auxiliary number
        // in binary form the middle in both directions
        aux_num = group_offset;
    }
    else {
        if (((group_offset + 1)
             - (1 << (group_no - 1))) % 2)
            op = 0; // Need to Insert 0 at middle
        else
            op = 1; // Need to Insert 1 at middle
        aux_num
            = ((group_offset) - (1 << (group_no - 1))) / 2;
    }
 
    return constructNthNumber(group_no, aux_num, op);
}
 
// Driver code
int main()
{
    int n = 9;
   
    // Function Call
    printf("%d", getNthNumber(n));
    return 0;
}


Java
// Efficient Java program to find n-th palindrome
class GFG {
 
    static int INT_SIZE = 32;
 
    // Construct the nth binary palindrome with the
    // given group number, aux_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 need to insert any bit in the middle
        if (op == 2) {
             
            // Length of the final binary representation
            len_f = 2 * group_no;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
 
            // Start filling the a[] from middle,
            // with the aux_num binary representation
            while (aux_num > 0) {
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + i]
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Insert bit 0 in the middle
        else if (op == 0) {
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 0;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                 
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i]
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
        else // Insert bit 1 in the middle
        {
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 1;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i]
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Convert the number to decimal from binary
        for (i = 0; i < len_f; i++)
            num += (1 << i) * a[i];
        return num;
    }
 
    // Will return the 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;
 
        // Add number of elements in all the groups,
        // until the group of the nth number is found
        while (count_temp < n) {
            group_no++;
 
            // Total number of elements until this group
            count_upto_group = count_temp;
            count_temp += 3 * (1 << (group_no - 1));
        }
 
        // Element's offset position in the group
        group_offset = n - count_upto_group - 1;
 
        // Finding which bit to be placed in the
        // middle and finding the number, which we
        // will fill from the middle in both
        // directions
        if ((group_offset + 1) <= (1 << (group_no - 1))) {
            op = 2; // No need to put extra bit in middle
 
            // We need to fill this auxiliary number
            // in binary form the middle in both directions
            aux_num = group_offset;
        }
        else {
            if (((group_offset + 1)
                 - (1 << (group_no - 1))) % 2 == 1)
                op = 0; // Need to Insert 0 at middle
            else
                op = 1; // Need to Insert 1 at middle
            aux_num
                = ((group_offset)
                - (1 << (group_no - 1))) / 2;
        }
 
        return constructNthNumber(group_no, aux_num, op);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 9;
       
        // Function Call
        System.out.printf("%d", getNthNumber(n));
    }
}
 
/* This code contributed by PrinciRaj1992 */


Python3
# Efficient Python3 program to find n-th palindrome
INT_SIZE = 32
 
# Construct the nth binary palindrome with the
# given group number, aux_number and operation type
 
 
def constructNthNumber(group_no, aux_num, op):
 
    a = [0] * INT_SIZE
    num, i = 0, 0
 
    # No need to insert any bit in the middle
    if op == 2:
 
        # Length of the final binary representation
        len_f = 2 * group_no
 
        # Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1
 
        # Start filling the a[] from middle,
        # with the aux_num binary representation
        while aux_num:
 
            # Get the auxiliary number's ith
            # bit and fill around middle
            a[group_no + i] = a[group_no - 1 - i] = \
                aux_num & 1
            aux_num = aux_num >> 1
            i += 1
 
    # Insert bit 0 in the middle
    elif op == 0:
 
        # Length of the final binary representation
        len_f = 2 * group_no + 1
 
        # Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1
        a[group_no] = 0
 
        # Start filling the a[] from middle, with
        # the aux_num binary representation
        while aux_num:
 
            # Get the auxiliary number's ith
            # bit and fill around middle
            a[group_no + 1 + i] = a[group_no - 1 - i] = \
                aux_num & 1
            aux_num = aux_num >> 1
            i += 1
 
    else:  # Insert bit 1 in the middle
 
        # Length of the final binary representation
        len_f = 2 * group_no + 1
 
        # Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1
        a[group_no] = 1
 
        # Start filling the a[] from middle, with
        # the aux_num binary representation
        while aux_num:
 
            # Get the auxiliary number's ith
            # bit and fill around middle
            a[group_no + 1 + i] = a[group_no - 1 - i] = \
                aux_num & 1
            aux_num = aux_num >> 1
            i += 1
 
    # Convert the number to decimal from binary
    for i in range(0, len_f):
        num += (1 << i) * a[i]
    return num
 
# Will return the nth binary palindrome number
 
 
def getNthNumber(n):
 
    group_no = 0
    count_upto_group, count_temp = 0, 1
 
    # Add number of elements in all the groups,
    # until the group of the nth number is found
    while count_temp < n:
 
        group_no += 1
 
        # Total number of elements until this group
        count_upto_group = count_temp
        count_temp += 3 * (1 << (group_no - 1))
 
    # Element's offset position in the group
    group_offset = n - count_upto_group - 1
 
    # Finding which bit to be placed in the
    # middle and finding the number, which we
    # will fill from the middle in both directions
    if (group_offset + 1) <= (1 << (group_no - 1)):
 
        op = 2  # No need to put extra bit in middle
 
        # We need to fill this auxiliary number
        # in binary form the middle in both directions
        aux_num = group_offset
 
    else:
 
        if (((group_offset + 1) -
             (1 << (group_no - 1))) % 2):
            op = 0  # Need to Insert 0 at middle
        else:
            op = 1  # Need to Insert 1 at middle
        aux_num = (((group_offset) -
                    (1 << (group_no - 1))) // 2)
 
    return constructNthNumber(group_no, aux_num, op)
 
 
# Driver code
if __name__ == "__main__":
 
    n = 9
     
    # Function Call
    print(getNthNumber(n))
 
# This code is contributed by Rituraj Jain


C#
// Efficient C# program to find n-th palindrome
using System;
 
class GFG {
 
    static int INT_SIZE = 32;
 
    // Construct the nth binary palindrome with the
    // given group number, aux_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 need to insert any bit in the middle
        if (op == 2) {
            
            // Length of the final binary representation
            len_f = 2 * group_no;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
 
            // Start filling the a[] from middle,
            // with the aux_num binary representation
            while (aux_num > 0) {
                 
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Insert bit 0 in the middle
        else if (op == 0) {
            
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 0;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                 
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
        else // Insert bit 1 in the middle
        {
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 1;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Convert the number to decimal from binary
        for (i = 0; i < len_f; i++)
            num += (1 << i) * a[i];
        return num;
    }
 
    // Will return the 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;
 
        // Add number of elements in all the groups,
        // until the group of the nth number is found
        while (count_temp < n) {
            group_no++;
 
            // Total number of elements until this group
            count_upto_group = count_temp;
            count_temp += 3 * (1 << (group_no - 1));
        }
 
        // Element's offset position in the group
        group_offset = n - count_upto_group - 1;
 
        // Finding which bit to be placed in the
        // middle and finding the number, which we
        // will fill from the middle in both
        // directions
        if ((group_offset + 1) <= (1 << (group_no - 1))) {
            op = 2; // No need to put extra bit in middle
 
            // We need to fill this auxiliary number
            // in binary form the middle in both directions
            aux_num = group_offset;
        }
        else {
            if (((group_offset + 1) - (1 << (group_no - 1)))
                    % 2
                == 1)
                op = 0; // Need to Insert 0 at middle
            else
                op = 1; // Need to Insert 1 at middle
            aux_num
                = ((group_offset) - (1 << (group_no - 1)))
                  / 2;
        }
 
        return constructNthNumber(group_no, aux_num, op);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int n = 9;
       
        // Function Call
        Console.Write("{0}", getNthNumber(n));
    }
}
 
// This code contributed by Rajput-Ji


PHP
> 1;
            $i++;
        }
    }
 
    // Insert bit 0 in the middle
    else if ($op == 0)
    {
        // Length of the final binary representation
        $len_f = 2 * $group_no + 1;
 
        // Fill first and last bit as 1
        $a[$len_f - 1] = $a[0] = 1;
        $a[$group_no] = 0;
 
        /* Start filling the a[] from middle, with
        the aux_num binary representation */
        while ($aux_num)
        {
            // Get the auxiliary number's ith bit and fill
            // around middle
            $a[$group_no + 1 + $i] = $a[$group_no - 1 - $i]
                                = $aux_num & 1;
            $aux_num = $aux_num >> 1;
            $i++;
        }
    }
    else     // Insert bit 1 in the middle
    {
        // Length of the final binary representation
        $len_f = 2 * $group_no + 1;
 
        // Fill first and last bit as 1
        $a[$len_f - 1] = $a[0] = 1;
        $a[$group_no] = 1;
 
        /* Start filling the a[] from middle, with
        the aux_num binary representation */
        while ($aux_num)
        {
            // Get the auxiliary number's ith bit and fill
            // around middle
            $a[$group_no + 1 + $i] = $a[$group_no - 1 - $i]
                                = $aux_num & 1;
            $aux_num = $aux_num >> 1;
            $i++;
        }
    }
 
    /* Convert the number to decimal from binary */
    for ($i = 0; $i < $len_f; $i++)
        $num += (1 << $i) * $a[$i];
    return $num;
}
 
/* Will return the nth binary palindrome number */
function getNthNumber($n)
{
    $group_no = 0;
    $count_upto_group = 0;
    $count_temp = 1;
    $op=$aux_num=0;
 
    /* Add number of elements in all the groups,
    until the group of the nth number is found */
    while ($count_temp < $n)
    {
        $group_no++;
 
        // Total number of elements until this group
        $count_upto_group = $count_temp;
        $count_temp += 3 * (1 << ($group_no - 1));
    }
 
    // Element's offset position in the group
    $group_offset = $n - $count_upto_group - 1;
 
    /* Finding which bit to be placed in the
    middle and finding the number, which we
    will fill from the middle in both
    directions */
    if (($group_offset + 1) <= (1 << ($group_no - 1)))
    {
        $op = 2; // No need to put extra bit in middle
 
        // We need to fill this auxiliary number
        // in binary form the middle in both directions
        $aux_num = $group_offset;
    }
    else
    {
        if ((($group_offset + 1) - (1 << ($group_no - 1))) % 2)
            $op = 0; // Need to Insert 0 at middle
        else
            $op = 1; // Need to Insert 1 at middle
        $aux_num = (int)((($group_offset) - (1 << ($group_no - 1))) / 2);
    }
 
    return constructNthNumber($group_no, $aux_num, $op);
}
 
    // Driver code
    $n = 9;
 
    // Function Call
    print(getNthNumber($n));
 
// This code is contributed by mits
?>


输出
27

此解决方案的时间复杂度为O(x) ,其中x是结果数。
请注意,x的值通常比n大得多。

方法2:使用BFS

首先,采用这种方法,我们只需将此字符串添加“ 11”到队列中即可。然后,对于每个字符串,我们有两种情况。 IE

  1. 如果偶数长度的CURR字符串然后在CURR字符串的中间加“0”“1”,并把它添加到队列。
  2. 如果curr字符串的长度为奇数,则将curr字符串的中字符添加到结果字符串,然后将其添加到队列中。

如果curr字符串的长度是偶数

如果curr字符串的长度为奇数

下面是上述方法的实现:

C++

// C++ program to find n-th palindrome
#include 
using namespace std;
 
// utility function which is used to
// convert binary string into integer
int convertStringToInt(string s)
{
    int num = 0;
 
    // convert binary string into integer
    for (int i = 0; i < s.size(); i++) {
        num = num * 2 + (s[i] - '0');
    }
    return num;
}
 
// function to find nth binary palindrome number
int getNthNumber(int n)
{
 
    // base case
    if (n == 1)
        return 1;
    n--;
 
    // stores the binary palindrome string
    queue q;
 
    // add 2nd binary palindrome string
    q.push("11");
 
    // runs till the nth binary palindrome number
    while (!q.empty()) {
        // remove curr binary palindrome string from queue
        string curr = q.front();
        q.pop();
        n--;
 
        // if n==0 then we find the n'th binary palindrome
        // so we return our answer
        if (!n) {
            return convertStringToInt(curr);
        }
 
        int mid = curr.size() / 2;
 
        // if length is even .so it is our first case
        // we have two choices
        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 .so it is our second case
        // we have only one choice
        else {
            string ch(1, curr[mid]);
            string temp = curr;
            temp.insert(mid, ch);
            q.push(temp);
        }
    }
 
    return 0;
}
 
// Driver Code
int main()
{
    int n = 9;
     
    // Function Call
    cout << getNthNumber(n);
}
 
// This code is contributed by Sagar Jangra and Naresh
// Saharan

Java

// Java program to find n-th palindrome
import java.io.*;
import java.util.*;
class GFG {
 
    // utility function which is used to
    // convert binary string into integer
    public static int convertStringToInt(String s)
    {
        int ans = 0;
 
        // convert binary string into integer
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1')
                ans += 1 << i;
        }
        return ans;
    }
 
    // function to find nth binary palindrome number
    public static int getNthNumber(int n)
    {
        // stores the binary palindrome string
        Queue q = new LinkedList<>();
 
        // base case
        if (n == 1)
            return 1;
        n = n - 1;
 
        // add 2nd binary palindrome string
        q.add("11");
 
        // runs till the nth binary palindrome number
        while (n-- > 0) {
 
            // remove curr binary palindrome string from
            // queue
            String curr = q.remove();
 
            // if n==0 then we find the n'th binary
            // palindrome so we return our answer
            if (n == 0)
                return convertStringToInt(curr);
 
            // calculate length of curr binary palindrome
            // string
            int len = curr.length();
 
            // if length is even .so it is our first case
            // we have two choices
            if (len % 2 == 0) {
                q.add(curr.substring(0, len / 2) + "0"
                      + curr.substring(len / 2));
                q.add(curr.substring(0, len / 2) + "1"
                      + curr.substring(len / 2));
            }
 
            // if length is odd .so it is our second case
            // we have only one choice
            else {
                char midChar = curr.charAt(len / 2);
                q.add(curr.substring(0, len / 2) + midChar
                      + curr.substring(len / 2));
            }
        }
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 9;
       
        // Function Call
        System.out.println(getNthNumber(n));
    }
}
// This code is contributed by Naresh Saharan and Sagar
// Jangra

Python3

# Python program to find n-th palindrome
 
# utility function which is used to
# convert binary string into integer
def convertStringToInt(s):
    ans = 0
     
    # convert binary string into integer
    for i in range(len(s)):
        ans = ans * 2 + (ord(s[i]) - ord('0'))
     
    return ans
 
# function to find nth binary palindrome number
def getNthNumber(n):
     
    # stores the binary palindrome string
    q = []
     
    # base case
    if(n == 1):
        return 1
    n = n - 1
     
    # add 2nd binary palindrome string
    q.append("11")
     
    # runs till the nth binary palindrome number
    while(len(q) != 0):
         
        # remove curr binary palindrome string from
        # queue
        curr = q.pop(0)
        n -= 1
         
        # if n==0 then we find the n'th binary
        # palindrome so we return our answer
        if(n ==0):
            return convertStringToInt(curr)
         
        # calculate length of curr binary palindrome
        # string
        lenn = len(curr)
         
        # if length is even .so it is our first case
        # we have two choices
        if (len(curr) % 2 == 0):
            q.append(curr[0:int(lenn/2)]+"0"+curr[int(lenn/2):])
            q.append(curr[0:int(lenn/2)]+"1"+curr[int(lenn/2):])
         
        # if length is odd .so it is our second case
        # we have only one choice
        else:
            midChar = curr[int(lenn/2)]
            q.append(curr[0:int(lenn/2)]+midChar+curr[int(lenn/2):])
         
    return 0
             
# Driver code
n = 9
 
# Function Call
print(getNthNumber(n))
 
# This code is contributed by avanitrachhadiya2155
输出
27

时间复杂度: O(N)
空间复杂度: O(N)

方法3:构建第n个回文

我们可以使用以下方法直接以其二进制表示形式构造第n个二进制回文。
如果我们观察到头几个二进制回文

*         | nth Binary  |
       n   | Palindrome  |     Group
           |             |
--------------------------- Group 0
    1 --->  1 (1)
    

Group 1 (Will have binary representation of length 2*(1)
and 2*(1) + 1)

    Fix the first and last bit as 1 and insert nothing
    (|) in between. Length is 2*(1)
    2 --->  1|1 (3)     

    Fix the first and last bit as 1 and insert bit 0
    in between. Length is 2*(1) + 1
    3 --->  101 (5)    

    Fix the first and last bit as 1 and insert bit 1 
    in between. Length is 2*(1) + 1 
    4 --->  111 (7)    
    F

Group 2 (Will have binary representation of length 
    2*(2) and 2*(2) + 1).  Fix the first and last 
    bit as 1 and insert nothing (|) at middle. 
    And put 0 in binary format in both directions 
    from middle. Length is 2*(2)
    5 --->  10|01       
    Fix the first and last bit as 1 and insert 
    nothing (|) at middle. And put 1 in binary 
    format in both directions from middle. 
    Length is 2*(2)
    6 --->  11|11      
    
    7 --->  10001      
    8 --->  10101     
    9 --->  11011     
    10 --->  11111      
    
Group 3 (Will have binary representation of 
        length 2*(3) and 2*(3) + 1)
    11 ---> 100|001    
    12 ---> 101|101    
    13 ---> 110|011    
    14 ---> 111|111  
    
    15 ---> 1000001  
    16 ---> 1001001  
    17 ---> 1010101  
    18 ---> 1011101  
    19 ---> 1100011  
    20 ---> 1101011  
    21 ---> 1110111    
    22 ---> 1111111 
-------------------- 

算法:
1)我们可以将回文数集划分为几组。
2)第n组将具有(2 ^(n-1)+ 2 ^ n = 3 * 2 ^(n-1))个二元回文数
3)使用给定的数字,我们可以找到它所属的组以及该组中的偏移量。
4)由于不考虑前导零,因此我们应使用位1作为二进制表示形式中数字的开始位和结束位
5)然后我们将根据groupno和groupoffset填充其他位
6)根据偏移量,我们可以找到应该在中间插入哪个位(|(nothing)或0或1),然后
应从中间向两个方向放置哪个数字(二进制形式)(1或2或3或4或..)

考虑下面的例子

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

// Efficient C program to find n-th palindrome
#include 
#define INT_SIZE 32
 
// Construct the nth binary palindrome with the
// given group number, aux_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 need to insert any bit in the middle
    if (op == 2) {
         
        // Length of the final binary representation
        len_f = 2 * group_no;
 
        // Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1;
 
        // Start filling the a[] from middle,
        // with the aux_num binary representation
        while (aux_num) {
             
            // Get the auxiliary number's ith bit and
            // fill around middle
            a[group_no + i]
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
 
    // Insert bit 0 in the middle
    else if (op == 0) {
         
        // Length of the final binary representation
        len_f = 2 * group_no + 1;
 
        // Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 0;
 
        // Start filling the a[] from middle, with
        // the aux_num binary representation
        while (aux_num) {
            // Get the auxiliary number's ith bit and fill
            // around middle
            a[group_no + 1 + i]
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
    else // Insert bit 1 in the middle
    {
        // Length of the final binary representation
        len_f = 2 * group_no + 1;
 
        // Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1;
        a[group_no] = 1;
 
        // Start filling the a[] from middle, with
        // the aux_num binary representation
        while (aux_num) {
             
            // Get the auxiliary number's ith bit and fill
            // around middle
            a[group_no + 1 + i]
                = a[group_no - 1 - i]
                = aux_num & 1;
            aux_num = aux_num >> 1;
            i++;
        }
    }
 
    // Convert the number to decimal from binary
    for (i = 0; i < len_f; i++)
        num += (1 << i) * a[i];
    return num;
}
 
// Will return the 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;
 
    // Add number of elements in all the groups,
    // until the group of the nth number is found
    while (count_temp < n) {
        group_no++;
 
        // Total number of elements until this group
        count_upto_group = count_temp;
        count_temp += 3 * (1 << (group_no - 1));
    }
 
    // Element's offset position in the group
    group_offset = n - count_upto_group - 1;
 
    // Finding which bit to be placed in the
    // middle and finding the number, which we
    // will fill from the middle in both
    // directions
    if ((group_offset + 1) <= (1 << (group_no - 1))) {
        op = 2; // No need to put extra bit in middle
 
        // We need to fill this auxiliary number
        // in binary form the middle in both directions
        aux_num = group_offset;
    }
    else {
        if (((group_offset + 1)
             - (1 << (group_no - 1))) % 2)
            op = 0; // Need to Insert 0 at middle
        else
            op = 1; // Need to Insert 1 at middle
        aux_num
            = ((group_offset) - (1 << (group_no - 1))) / 2;
    }
 
    return constructNthNumber(group_no, aux_num, op);
}
 
// Driver code
int main()
{
    int n = 9;
   
    // Function Call
    printf("%d", getNthNumber(n));
    return 0;
}

Java

// Efficient Java program to find n-th palindrome
class GFG {
 
    static int INT_SIZE = 32;
 
    // Construct the nth binary palindrome with the
    // given group number, aux_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 need to insert any bit in the middle
        if (op == 2) {
             
            // Length of the final binary representation
            len_f = 2 * group_no;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
 
            // Start filling the a[] from middle,
            // with the aux_num binary representation
            while (aux_num > 0) {
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + i]
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Insert bit 0 in the middle
        else if (op == 0) {
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 0;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                 
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i]
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
        else // Insert bit 1 in the middle
        {
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 1;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i]
                    = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Convert the number to decimal from binary
        for (i = 0; i < len_f; i++)
            num += (1 << i) * a[i];
        return num;
    }
 
    // Will return the 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;
 
        // Add number of elements in all the groups,
        // until the group of the nth number is found
        while (count_temp < n) {
            group_no++;
 
            // Total number of elements until this group
            count_upto_group = count_temp;
            count_temp += 3 * (1 << (group_no - 1));
        }
 
        // Element's offset position in the group
        group_offset = n - count_upto_group - 1;
 
        // Finding which bit to be placed in the
        // middle and finding the number, which we
        // will fill from the middle in both
        // directions
        if ((group_offset + 1) <= (1 << (group_no - 1))) {
            op = 2; // No need to put extra bit in middle
 
            // We need to fill this auxiliary number
            // in binary form the middle in both directions
            aux_num = group_offset;
        }
        else {
            if (((group_offset + 1)
                 - (1 << (group_no - 1))) % 2 == 1)
                op = 0; // Need to Insert 0 at middle
            else
                op = 1; // Need to Insert 1 at middle
            aux_num
                = ((group_offset)
                - (1 << (group_no - 1))) / 2;
        }
 
        return constructNthNumber(group_no, aux_num, op);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 9;
       
        // Function Call
        System.out.printf("%d", getNthNumber(n));
    }
}
 
/* This code contributed by PrinciRaj1992 */

Python3

# Efficient Python3 program to find n-th palindrome
INT_SIZE = 32
 
# Construct the nth binary palindrome with the
# given group number, aux_number and operation type
 
 
def constructNthNumber(group_no, aux_num, op):
 
    a = [0] * INT_SIZE
    num, i = 0, 0
 
    # No need to insert any bit in the middle
    if op == 2:
 
        # Length of the final binary representation
        len_f = 2 * group_no
 
        # Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1
 
        # Start filling the a[] from middle,
        # with the aux_num binary representation
        while aux_num:
 
            # Get the auxiliary number's ith
            # bit and fill around middle
            a[group_no + i] = a[group_no - 1 - i] = \
                aux_num & 1
            aux_num = aux_num >> 1
            i += 1
 
    # Insert bit 0 in the middle
    elif op == 0:
 
        # Length of the final binary representation
        len_f = 2 * group_no + 1
 
        # Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1
        a[group_no] = 0
 
        # Start filling the a[] from middle, with
        # the aux_num binary representation
        while aux_num:
 
            # Get the auxiliary number's ith
            # bit and fill around middle
            a[group_no + 1 + i] = a[group_no - 1 - i] = \
                aux_num & 1
            aux_num = aux_num >> 1
            i += 1
 
    else:  # Insert bit 1 in the middle
 
        # Length of the final binary representation
        len_f = 2 * group_no + 1
 
        # Fill first and last bit as 1
        a[len_f - 1] = a[0] = 1
        a[group_no] = 1
 
        # Start filling the a[] from middle, with
        # the aux_num binary representation
        while aux_num:
 
            # Get the auxiliary number's ith
            # bit and fill around middle
            a[group_no + 1 + i] = a[group_no - 1 - i] = \
                aux_num & 1
            aux_num = aux_num >> 1
            i += 1
 
    # Convert the number to decimal from binary
    for i in range(0, len_f):
        num += (1 << i) * a[i]
    return num
 
# Will return the nth binary palindrome number
 
 
def getNthNumber(n):
 
    group_no = 0
    count_upto_group, count_temp = 0, 1
 
    # Add number of elements in all the groups,
    # until the group of the nth number is found
    while count_temp < n:
 
        group_no += 1
 
        # Total number of elements until this group
        count_upto_group = count_temp
        count_temp += 3 * (1 << (group_no - 1))
 
    # Element's offset position in the group
    group_offset = n - count_upto_group - 1
 
    # Finding which bit to be placed in the
    # middle and finding the number, which we
    # will fill from the middle in both directions
    if (group_offset + 1) <= (1 << (group_no - 1)):
 
        op = 2  # No need to put extra bit in middle
 
        # We need to fill this auxiliary number
        # in binary form the middle in both directions
        aux_num = group_offset
 
    else:
 
        if (((group_offset + 1) -
             (1 << (group_no - 1))) % 2):
            op = 0  # Need to Insert 0 at middle
        else:
            op = 1  # Need to Insert 1 at middle
        aux_num = (((group_offset) -
                    (1 << (group_no - 1))) // 2)
 
    return constructNthNumber(group_no, aux_num, op)
 
 
# Driver code
if __name__ == "__main__":
 
    n = 9
     
    # Function Call
    print(getNthNumber(n))
 
# This code is contributed by Rituraj Jain

C#

// Efficient C# program to find n-th palindrome
using System;
 
class GFG {
 
    static int INT_SIZE = 32;
 
    // Construct the nth binary palindrome with the
    // given group number, aux_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 need to insert any bit in the middle
        if (op == 2) {
            
            // Length of the final binary representation
            len_f = 2 * group_no;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
 
            // Start filling the a[] from middle,
            // with the aux_num binary representation
            while (aux_num > 0) {
                 
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Insert bit 0 in the middle
        else if (op == 0) {
            
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 0;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                 
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
        else // Insert bit 1 in the middle
        {
            // Length of the final binary representation
            len_f = 2 * group_no + 1;
 
            // Fill first and last bit as 1
            a[len_f - 1] = a[0] = 1;
            a[group_no] = 1;
 
            // Start filling the a[] from middle, with
            // the aux_num binary representation
            while (aux_num > 0) {
                // Get the auxiliary number's ith bit and
                // fill around middle
                a[group_no + 1 + i] = a[group_no - 1 - i]
                    = aux_num & 1;
                aux_num = aux_num >> 1;
                i++;
            }
        }
 
        // Convert the number to decimal from binary
        for (i = 0; i < len_f; i++)
            num += (1 << i) * a[i];
        return num;
    }
 
    // Will return the 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;
 
        // Add number of elements in all the groups,
        // until the group of the nth number is found
        while (count_temp < n) {
            group_no++;
 
            // Total number of elements until this group
            count_upto_group = count_temp;
            count_temp += 3 * (1 << (group_no - 1));
        }
 
        // Element's offset position in the group
        group_offset = n - count_upto_group - 1;
 
        // Finding which bit to be placed in the
        // middle and finding the number, which we
        // will fill from the middle in both
        // directions
        if ((group_offset + 1) <= (1 << (group_no - 1))) {
            op = 2; // No need to put extra bit in middle
 
            // We need to fill this auxiliary number
            // in binary form the middle in both directions
            aux_num = group_offset;
        }
        else {
            if (((group_offset + 1) - (1 << (group_no - 1)))
                    % 2
                == 1)
                op = 0; // Need to Insert 0 at middle
            else
                op = 1; // Need to Insert 1 at middle
            aux_num
                = ((group_offset) - (1 << (group_no - 1)))
                  / 2;
        }
 
        return constructNthNumber(group_no, aux_num, op);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int n = 9;
       
        // Function Call
        Console.Write("{0}", getNthNumber(n));
    }
}
 
// This code contributed by Rajput-Ji

的PHP

> 1;
            $i++;
        }
    }
 
    // Insert bit 0 in the middle
    else if ($op == 0)
    {
        // Length of the final binary representation
        $len_f = 2 * $group_no + 1;
 
        // Fill first and last bit as 1
        $a[$len_f - 1] = $a[0] = 1;
        $a[$group_no] = 0;
 
        /* Start filling the a[] from middle, with
        the aux_num binary representation */
        while ($aux_num)
        {
            // Get the auxiliary number's ith bit and fill
            // around middle
            $a[$group_no + 1 + $i] = $a[$group_no - 1 - $i]
                                = $aux_num & 1;
            $aux_num = $aux_num >> 1;
            $i++;
        }
    }
    else     // Insert bit 1 in the middle
    {
        // Length of the final binary representation
        $len_f = 2 * $group_no + 1;
 
        // Fill first and last bit as 1
        $a[$len_f - 1] = $a[0] = 1;
        $a[$group_no] = 1;
 
        /* Start filling the a[] from middle, with
        the aux_num binary representation */
        while ($aux_num)
        {
            // Get the auxiliary number's ith bit and fill
            // around middle
            $a[$group_no + 1 + $i] = $a[$group_no - 1 - $i]
                                = $aux_num & 1;
            $aux_num = $aux_num >> 1;
            $i++;
        }
    }
 
    /* Convert the number to decimal from binary */
    for ($i = 0; $i < $len_f; $i++)
        $num += (1 << $i) * $a[$i];
    return $num;
}
 
/* Will return the nth binary palindrome number */
function getNthNumber($n)
{
    $group_no = 0;
    $count_upto_group = 0;
    $count_temp = 1;
    $op=$aux_num=0;
 
    /* Add number of elements in all the groups,
    until the group of the nth number is found */
    while ($count_temp < $n)
    {
        $group_no++;
 
        // Total number of elements until this group
        $count_upto_group = $count_temp;
        $count_temp += 3 * (1 << ($group_no - 1));
    }
 
    // Element's offset position in the group
    $group_offset = $n - $count_upto_group - 1;
 
    /* Finding which bit to be placed in the
    middle and finding the number, which we
    will fill from the middle in both
    directions */
    if (($group_offset + 1) <= (1 << ($group_no - 1)))
    {
        $op = 2; // No need to put extra bit in middle
 
        // We need to fill this auxiliary number
        // in binary form the middle in both directions
        $aux_num = $group_offset;
    }
    else
    {
        if ((($group_offset + 1) - (1 << ($group_no - 1))) % 2)
            $op = 0; // Need to Insert 0 at middle
        else
            $op = 1; // Need to Insert 1 at middle
        $aux_num = (int)((($group_offset) - (1 << ($group_no - 1))) / 2);
    }
 
    return constructNthNumber($group_no, $aux_num, $op);
}
 
    // Driver code
    $n = 9;
 
    // Function Call
    print(getNthNumber($n));
 
// This code is contributed by mits
?>
输出
27

时间复杂度: O(1)。