Find the Kth smallest odd length palindrome number
Given a positive integer K, the task is to find Kth smallest palindromic number odd length.
Examples:
Input: K = 5
Output: 5
Explanation:
The palindromic numbers of odd lengths is {1, 2, 3, 4, 5, 6, 7, …, }. The 5th smallest palindromic numbers is 5.
Input: K = 10
Output: 101
Approach: The given problem can be solved based on the following observations:
- The first Palindromic Numbers of length 1 are 1, 2, 3, 4, 5, 6, 7, 8, and 9.
- The first Palindromic Numbers of length 3 is 101, which is the 10th smallest odd length palindrome number. Similarly, 11th, 12th, 13th, …, 99th smallest palindromic numbers are 111, 121, 131 …, 999 respectively.
- Therefore, the Kth smallest odd length palindrome number can be formed by joining K and the reverse of K except the last digit.
From the above observations, the Kth smallest odd length palindromic number is given by appending the reverse of all the digits of K except the last one at the end of K.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int oddLengthPalindrome( int k)
{
int palin = k;
k = k / 10;
while (k > 0)
{
int rev = k % 10;
palin = (palin * 10) + rev;
k = k / 10;
}
return palin;
}
int main()
{
int k = 504;
cout << oddLengthPalindrome(k);
}
|
Java
import java.util.*;
import java.lang.*;
class GFG{
static int oddLengthPalindrome( int k)
{
int palin = k;
k = k / 10 ;
while (k > 0 )
{
int rev = k % 10 ;
palin = (palin * 10 ) + rev;
k = k / 10 ;
}
return palin;
}
public static void main(String[] args)
{
int k = 504 ;
System.out.println(oddLengthPalindrome(k));
}
}
|
Python3
def oddLengthPalindrome(K):
palin = K
K = K / / 10
while (K > 0 ):
rev = K % 10
palin = palin * 10 + rev
K = K / / 10
return palin
if __name__ = = '__main__' :
K = 504
print (oddLengthPalindrome(K))
|
C#
using System;
class GFG{
static int oddLengthPalindrome( int k)
{
int palin = k;
k = k / 10;
while (k > 0)
{
int rev = k % 10;
palin = (palin * 10) + rev;
k = k / 10;
}
return palin;
}
static void Main( string [] args)
{
int k = 504;
Console.WriteLine(oddLengthPalindrome(k));
}
}
|
Javascript
<script>
function oddLengthPalindrome(k)
{
let palin = k;
k = Math.floor(k / 10);
while (k > 0)
{
let rev = k % 10;
palin = (palin * 10) + rev;
k = Math.floor(k / 10);
}
return palin;
}
let k = 504;
document.write(oddLengthPalindrome(k));
</script>
|
Time Complexity: O(log10K)
Auxiliary Space: O(1)
Last Updated :
22 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...