第 N 个偶数长度回文
给定一个数字 n 作为字符串,找到第 n 个偶数长度的正回文数。
例子:
Input : n = "1"
Output : 11
1st even-length palindrome is 11 .
Input : n = "10"
Output : 1001
The first 10 even-length palindrome numbers are 11, 22,
33, 44, 55, 66, 77, 88, 99 and 1001.
因为,它是一个偶数长度的回文,所以它的前半部分应该等于后半部分的反转,长度将是 2、4、6、8 ...。要评估第 n 个回文数,我们只看第 10 个偶数长度的回文数 11、22、33、44、55、66、77、88、99 和 1001。这里,第 n 个回文数是 nn',其中 n' 是 n 的倒数。因此我们只需要以连续的方式写 n 和 n' ,其中 n' 是 n 的倒数。
下面是这种方法的实现。
C++
// C++ program to find n=th even length string.
#include
using namespace std;
// Function to find nth even length Palindrome
string evenlength(string n)
{
// string r to store resultant
// palindrome. Initialize same as s
string res = n;
// In this loop string r stores
// reverse of string s after the
// string s in consecutive manner .
for (int j = n.length() - 1; j >= 0; --j)
res += n[j];
return res;
}
// Driver code
int main()
{
string n = "10";
// Function call
cout << evenlength(n);
return 0;
}
Java
// Java program to find nth even length Palindrome
import java.io.*;
class GFG
{
// Function to find nth even length Palindrome
static String evenlength(String n)
{
// string r to store resultant
// palindrome. Initialize same as s
String res = n;
// In this loop string r stores
// reverse of string s after the
// string s in consecutive manner
for (int j = n.length() - 1; j >= 0; --j)
res += n.charAt(j);
return res;
}
// Driver code
public static void main(String[] args)
{
String n = "10";
// Function call
System.out.println(evenlength(n));
}
}
// Contributed by Pramod Kumar
Python3
# Python3 program to find n=th even
# length string.
import math as mt
# Function to find nth even length
# Palindrome
def evenlength(n):
# string r to store resultant
# palindrome. Initialize same as s
res = n
# In this loop string r stores
# reverse of string s after the
# string s in consecutive manner .
for j in range(len(n) - 1, -1, -1):
res += n[j]
return res
# Driver code
n = "10"
# Function call
print(evenlength(n))
# This code is contributed by
# Mohit kumar 29
C#
// C# program to find nth even
// length Palindrome
using System;
class GFG {
// Function to find nth even
// length Palindrome
static string evenlength(string n)
{
// string r to store resultant
// palindrome. Initialize same
// as s
string res = n;
// In this loop string r stores
// reverse of string s after
// the string s in consecutive
// manner
for (int j = n.Length - 1; j >= 0; --j)
res += n[j];
return res;
}
// Driver code
public static void Main()
{
string n = "10";
// Function call
Console.WriteLine(evenlength(n));
}
}
// This code is contributed by vt_m.
PHP
= 0; --$j)
$res = $res . $n[$j];
return $res;
}
// Driver code
$n = "10";
// Function call
echo evenlength($n);
// This code is contributed by ita_c
?>
Javascript
输出
1001
时间复杂度: O(n)