📜  K位第N个回文

📅  最后修改于: 2021-05-05 00:33:47             🧑  作者: Mango

给定两个整数nk ,找到k个数字的按字典顺序排列的n回文。

例子:

Input  : n = 5, k = 4
Output : 1441
Explanation:
4 digit lexicographical palindromes are:
1001, 1111, 1221, 1331, 1441
5th palindrome = 1441

Input  :  n = 4, k = 6
Output : 103301

天真的方法

蛮力是从最小的k数字开始循环,并检查每个数字是否是回文。如果它是回文数,则递减k的值。因此,循环一直运行到k耗尽为止。

C++
// A naive approach of C++ program of finding nth
// palindrome of k digit
#include
using namespace std;
  
// Utility function to reverse the number n
int reverseNum(int n)
{
    int rem, rev=0;
    while (n)
    {
        rem = n % 10;
        rev = rev * 10 + rem;
        n /= 10;
    }
    return rev;
}
  
// Boolean Function to check for palindromic
// number
bool isPalindrom(int num)
{
    return num == reverseNum(num);
}
  
// Function for finding nth palindrome of k digits
int nthPalindrome(int n,int k)
{
    // Get the smallest k digit number
    int num = (int)pow(10, k-1);
  
    while (true)
    {
        // check the number is palindrom or not
        if (isPalindrom(num))
            --n;
  
        // if n'th palindrome found break the loop
        if (!n)
            break;
  
        // Increment number for checking next palindrome
        ++num;
    }
  
    return num;
}
  
// Driver code
int main()
{
    int n = 6, k = 5;
    printf("%dth palindrome of %d digit = %d\n",
           n, k, nthPalindrome(n, k));
  
    n = 10, k = 6;
    printf("%dth palindrome of %d digit = %d",
           n, k, nthPalindrome(n, k));
    return 0;
}


Java
// A naive approach of Java program of finding nth
// palindrome of k digit
import java.util.*;
  
class GFG
{
// Utility function to reverse the number n
static int reverseNum(int n)
{
    int rem, rev = 0;
    while (n > 0)
    {
        rem = n % 10;
        rev = rev * 10 + rem;
        n /= 10;
    }
    return rev;
}
  
// Boolean Function to check for palindromic
// number
static boolean isPalindrom(int num)
{
    return num == reverseNum(num);
}
  
// Function for finding nth palindrome of k digits
static int nthPalindrome(int n, int k)
{
    // Get the smallest k digit number
    int num = (int)Math.pow(10, k-1);
  
    while (true)
    {
        // check the number is palindrom or not
        if (isPalindrom(num))
            --n;
  
        // if n'th palindrome found break the loop
        if (n == 0)
            break;
  
        // Increment number for checking next palindrome
        ++num;
    }
  
    return num;
}
  
// Driver code
public static void main(String[] args)
{
    int n = 6, k = 5;
    System.out.println(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
  
    n = 10; k = 6;
    System.out.println(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
}
}
  
// This code is contributed by mits


Python3
# A naive approach of Python3 program 
# of finding nth palindrome of k digit 
import math;
# Utility function to 
# reverse the number n 
def reverseNum(n): 
    rev = 0; 
    while (n): 
        rem = n % 10; 
        rev = (rev * 10) + rem; 
        n = int(n / 10); 
   
    return rev; 
  
# Boolean Function to check for 
# palindromic number 
def isPalindrom(num):
    return num == reverseNum(num); 
  
# Function for finding nth 
# palindrome of k digits 
def nthPalindrome(n, k): 
    # Get the smallest k digit number 
    num = math.pow(10, k - 1); 
  
    while (True): 
        # check the number is 
        # palindrom or not 
        if (isPalindrom(num)): 
            n-=1; 
  
        # if n'th palindrome found 
        # break the loop 
        if (not n): 
            break; 
  
        # Increment number for checking
        # next palindrome 
        num+=1; 
  
    return int(num); 
  
# Driver code 
n = 6;
k = 5; 
print(n,"th palindrome of",k,"digit =",nthPalindrome(n, k)); 
  
n = 10;
k = 6; 
print(n,"th palindrome of",k,"digit =",nthPalindrome(n, k));
  
# This code is contributed by mits


C#
// A naive approach of C# program of finding nth
// palindrome of k digit
using System;
  
class GFG
{
// Utility function to reverse the number n
static int reverseNum(int n)
{
    int rem, rev = 0;
    while (n > 0)
    {
        rem = n % 10;
        rev = rev * 10 + rem;
        n /= 10;
    }
    return rev;
}
  
// Boolean Function to check for palindromic
// number
static bool isPalindrom(int num)
{
    return num == reverseNum(num);
}
  
// Function for finding nth palindrome of k digits
static int nthPalindrome(int n, int k)
{
    // Get the smallest k digit number
    int num = (int)Math.Pow(10, k-1);
  
    while (true)
    {
        // check the number is palindrom or not
        if (isPalindrom(num))
            --n;
  
        // if n'th palindrome found break the loop
        if (n == 0)
            break;
  
        // Increment number for checking next palindrome
        ++num;
    }
  
    return num;
}
  
// Driver code
public static void Main()
{
    int n = 6, k = 5;
    Console.WriteLine(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
  
    n = 10; k = 6;
    Console.WriteLine(n + "th palindrome of " + k + " digit = " + nthPalindrome(n, k));
}
}
  
// This code is contributed 
// by Akanksha Rai


PHP


C++
// C++ program of finding nth palindrome
// of k digit
#include
using namespace std;
  
void nthPalindrome(int n, int k)
{
    // Determine the first half digits
    int temp = (k & 1) ? (k / 2) : (k/2 - 1);
    int palindrome = (int)pow(10, temp);
    palindrome += n - 1;
  
    // Print the first half digits of palindrome
    printf("%d", palindrome);
  
    // If k is odd, truncate the last digit
    if (k & 1)
        palindrome /= 10;
  
    // print the last half digits of palindrome
    while (palindrome)
    {
        printf("%d", palindrome % 10);
        palindrome /= 10;
    }
    printf("\n");
}
  
// Driver code
int main()
{
    int n = 6, k = 5;
    printf("%dth palindrome of %d digit = ",n ,k);
    nthPalindrome(n ,k);
  
    n = 10, k = 6;
    printf("%dth palindrome of %d digit = ",n ,k);
    nthPalindrome(n, k);
    return 0;
}


Java
// Java program of finding nth palindrome
// of k digit
  
  
class GFG{
static void nthPalindrome(int n, int k)
{
    // Determine the first half digits
    int temp = (k & 1)!=0 ? (k / 2) : (k/2 - 1);
    int palindrome = (int)Math.pow(10, temp);
    palindrome += n - 1;
  
    // Print the first half digits of palindrome
    System.out.print(palindrome);
  
    // If k is odd, truncate the last digit
    if ((k & 1)>0)
        palindrome /= 10;
  
    // print the last half digits of palindrome
    while (palindrome>0)
    {
        System.out.print(palindrome % 10);
        palindrome /= 10;
    }
    System.out.println("");
}
  
// Driver code
public static void main(String[] args)
{
    int n = 6, k = 5;
    System.out.print(n+"th palindrome of "+k+" digit = ");
    nthPalindrome(n ,k);
  
    n = 10;
    k = 6;
    System.out.print(n+"th palindrome of "+k+" digit = ");
    nthPalindrome(n, k);
  
}
}
// This code is contributed by mits


Python3
# Python3 program of finding nth palindrome
# of k digit
  
def nthPalindrome(n, k):
  
    # Determine the first half digits
    if(k & 1):
        temp = k // 2
    else:
        temp = k // 2 - 1
  
    palindrome = 10**temp
    palindrome = palindrome + n - 1
  
    # Print the first half digits of palindrome
    print(palindrome, end="")
  
    # If k is odd, truncate the last digit
    if(k & 1):
        palindrome = palindrome // 10
  
    # print the last half digits of palindrome
    while(palindrome):
        print(palindrome % 10, end="")
        palindrome = palindrome // 10
  
# Driver code
if __name__=='__main__':
    n = 6
    k = 5
    print(n, "th palindrome of", k, " digit = ", end=" ")
    nthPalindrome(n, k)
    print()
    n = 10
    k = 6
    print(n, "th palindrome of", k, "digit = ",end=" ")
    nthPalindrome(n, k)
  
# This code is contributed by
# Sanjit_Prasad


C#
// C# program of finding nth palindrome 
// of k digit 
using System;
  
class GFG
{
static void nthPalindrome(int n, int k) 
{ 
    // Determine the first half digits 
    int temp = (k & 1) != 0 ? (k / 2) : (k / 2 - 1); 
    int palindrome = (int)Math.Pow(10, temp); 
    palindrome += n - 1; 
  
    // Print the first half digits 
    // of palindrome 
    Console.Write(palindrome); 
  
    // If k is odd, truncate the last digit 
    if ((k & 1) > 0) 
        palindrome /= 10; 
  
    // print the last half digits 
    // of palindrome 
    while (palindrome>0) 
    { 
        Console.Write(palindrome % 10); 
        palindrome /= 10; 
    } 
    Console.WriteLine(""); 
} 
  
// Driver code 
static public void Main ()
{
    int n = 6, k = 5; 
    Console.Write(n+"th palindrome of " + k + 
                                " digit = "); 
    nthPalindrome(n, k); 
      
    n = 10; 
    k = 6; 
    Console.Write(n+"th palindrome of " + k + 
                                " digit = "); 
    nthPalindrome(n, k); 
} 
} 
  
// This code is contributed by ajit


PHP
 0)
    {
        print($palindrome % 10);
        $palindrome = (int)($palindrome / 10);
    }
    print("\n");
}
  
// Driver code
$n = 6;
$k = 5;
print($n."th palindrome of $k digit = ");
nthPalindrome($n, $k);
  
$n = 10; 
$k = 6;
print($n."th palindrome of $k digit = ");
nthPalindrome($n, $k);
  
// This code is contributed by mits
?>


输出:

6th palindrome of 5 digit = 10501
10th palindrome of 6 digit = 109901

时间复杂度: O(10 k )
辅助空间: O(1)

高效的方法

一种有效的方法是寻找模式。根据回文的性质,前半位数与后半位数相反。因此,我们只需要查找前半个数字,因为其余半数很容易生成。让我们假设k = 8,最小回文总是从1开始作为前导数字,并像数字的前4个数字一样。

First half values for k = 8
1st: 1000
2nd: 1001
3rd: 1002
...
...
100th: 1099

So we can easily write the above sequence for nth
palindrome as: (n-1) + 1000
For k digit number, we can generalize above formula as:

If k is odd
=> num = (n-1) + 10k/2
else 
=> num = (n-1) + 10k/2 - 1 

Now rest half digits can be expanded by just 
printing the value of num in reverse order. 
But before this if k is odd then we have to truncate 
the last digit of a value num 

插图:
n = 6 k = 5

  1. 确定前半位数的位数= floor(5/2)= 2
  2. 使用公式:num =(6-1)+ 10 2 = 105
  3. 通过反转num的值来扩展其余半位数。
    最终答案将是10501

以下是上述步骤的执行

C++

// C++ program of finding nth palindrome
// of k digit
#include
using namespace std;
  
void nthPalindrome(int n, int k)
{
    // Determine the first half digits
    int temp = (k & 1) ? (k / 2) : (k/2 - 1);
    int palindrome = (int)pow(10, temp);
    palindrome += n - 1;
  
    // Print the first half digits of palindrome
    printf("%d", palindrome);
  
    // If k is odd, truncate the last digit
    if (k & 1)
        palindrome /= 10;
  
    // print the last half digits of palindrome
    while (palindrome)
    {
        printf("%d", palindrome % 10);
        palindrome /= 10;
    }
    printf("\n");
}
  
// Driver code
int main()
{
    int n = 6, k = 5;
    printf("%dth palindrome of %d digit = ",n ,k);
    nthPalindrome(n ,k);
  
    n = 10, k = 6;
    printf("%dth palindrome of %d digit = ",n ,k);
    nthPalindrome(n, k);
    return 0;
}

Java

// Java program of finding nth palindrome
// of k digit
  
  
class GFG{
static void nthPalindrome(int n, int k)
{
    // Determine the first half digits
    int temp = (k & 1)!=0 ? (k / 2) : (k/2 - 1);
    int palindrome = (int)Math.pow(10, temp);
    palindrome += n - 1;
  
    // Print the first half digits of palindrome
    System.out.print(palindrome);
  
    // If k is odd, truncate the last digit
    if ((k & 1)>0)
        palindrome /= 10;
  
    // print the last half digits of palindrome
    while (palindrome>0)
    {
        System.out.print(palindrome % 10);
        palindrome /= 10;
    }
    System.out.println("");
}
  
// Driver code
public static void main(String[] args)
{
    int n = 6, k = 5;
    System.out.print(n+"th palindrome of "+k+" digit = ");
    nthPalindrome(n ,k);
  
    n = 10;
    k = 6;
    System.out.print(n+"th palindrome of "+k+" digit = ");
    nthPalindrome(n, k);
  
}
}
// This code is contributed by mits

Python3

# Python3 program of finding nth palindrome
# of k digit
  
def nthPalindrome(n, k):
  
    # Determine the first half digits
    if(k & 1):
        temp = k // 2
    else:
        temp = k // 2 - 1
  
    palindrome = 10**temp
    palindrome = palindrome + n - 1
  
    # Print the first half digits of palindrome
    print(palindrome, end="")
  
    # If k is odd, truncate the last digit
    if(k & 1):
        palindrome = palindrome // 10
  
    # print the last half digits of palindrome
    while(palindrome):
        print(palindrome % 10, end="")
        palindrome = palindrome // 10
  
# Driver code
if __name__=='__main__':
    n = 6
    k = 5
    print(n, "th palindrome of", k, " digit = ", end=" ")
    nthPalindrome(n, k)
    print()
    n = 10
    k = 6
    print(n, "th palindrome of", k, "digit = ",end=" ")
    nthPalindrome(n, k)
  
# This code is contributed by
# Sanjit_Prasad

C#

// C# program of finding nth palindrome 
// of k digit 
using System;
  
class GFG
{
static void nthPalindrome(int n, int k) 
{ 
    // Determine the first half digits 
    int temp = (k & 1) != 0 ? (k / 2) : (k / 2 - 1); 
    int palindrome = (int)Math.Pow(10, temp); 
    palindrome += n - 1; 
  
    // Print the first half digits 
    // of palindrome 
    Console.Write(palindrome); 
  
    // If k is odd, truncate the last digit 
    if ((k & 1) > 0) 
        palindrome /= 10; 
  
    // print the last half digits 
    // of palindrome 
    while (palindrome>0) 
    { 
        Console.Write(palindrome % 10); 
        palindrome /= 10; 
    } 
    Console.WriteLine(""); 
} 
  
// Driver code 
static public void Main ()
{
    int n = 6, k = 5; 
    Console.Write(n+"th palindrome of " + k + 
                                " digit = "); 
    nthPalindrome(n, k); 
      
    n = 10; 
    k = 6; 
    Console.Write(n+"th palindrome of " + k + 
                                " digit = "); 
    nthPalindrome(n, k); 
} 
} 
  
// This code is contributed by ajit

的PHP

 0)
    {
        print($palindrome % 10);
        $palindrome = (int)($palindrome / 10);
    }
    print("\n");
}
  
// Driver code
$n = 6;
$k = 5;
print($n."th palindrome of $k digit = ");
nthPalindrome($n, $k);
  
$n = 10; 
$k = 6;
print($n."th palindrome of $k digit = ");
nthPalindrome($n, $k);
  
// This code is contributed by mits
?>

输出:

6th palindrome of 5 digit = 10501
10th palindrome of 6 digit = 109901

时间复杂度: O(k)
辅助空间: O(1)

参考:
http://stackoverflow.com/questions/11925840/how-to-calculate-nth-n-digit-palindrome-高效地