Nth Even length Palindrome
Given a number n as a string, find the nth even-length positive palindrome number .
Examples:
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.
As, it is a even-length palindrome so its first half should be equal to reverse of second half and length will be 2, 4, 6, 8 …. To evaluate nth palindrome let’s just see 1st 10 even-length palindrome numbers 11, 22, 33, 44, 55, 66, 77, 88, 99 and 1001 . Here, nth palindrome is nn’ where n’ is reverse of n . Thus we just have to write n and n’ in a consecutive manner where n’ is reverse of n .
Below is the implementation of this approach.
C++
#include <bits/stdc++.h>
using namespace std;
string evenlength(string n)
{
string res = n;
for ( int j = n.length() - 1; j >= 0; --j)
res += n[j];
return res;
}
int main()
{
string n = "10" ;
cout << evenlength(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static String evenlength(String n)
{
String res = n;
for ( int j = n.length() - 1 ; j >= 0 ; --j)
res += n.charAt(j);
return res;
}
public static void main(String[] args)
{
String n = "10" ;
System.out.println(evenlength(n));
}
}
|
Python3
import math as mt
def evenlength(n):
res = n
for j in range ( len (n) - 1 , - 1 , - 1 ):
res + = n[j]
return res
n = "10"
print (evenlength(n))
|
C#
using System;
class GFG {
static string evenlength( string n)
{
string res = n;
for ( int j = n.Length - 1; j >= 0; --j)
res += n[j];
return res;
}
public static void Main()
{
string n = "10" ;
Console.WriteLine(evenlength(n));
}
}
|
PHP
<?php
function evenlength( $n )
{
$res = $n ;
for ( $j = strlen ( $n ) - 1; $j >= 0; -- $j )
$res = $res . $n [ $j ];
return $res ;
}
$n = "10" ;
echo evenlength( $n );
?>
|
Javascript
<script>
function evenlength(n)
{
let res = n;
for (let j = n.length - 1; j >= 0; --j)
res += n[j];
return res;
}
let n = "10" ;
document.write(evenlength(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
14 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...