N’th palindrome of K digits in C++


To find the n-th palindrome of k digits, we can iterate from the first k digits number till we find the n-th palindrome number. This approach is not efficient. You can try it yourself.

Now, let's see the efficient approach to find the n-th palindrome of k digits.

There are two halves in the numbers. The first half is equal to the reverse of the second half.

The first half of the n-th number with k digits are

If k is odd then (n - 1) + 10k/2else(n-1)+10k/2-1

The second half of the n-th number with k digits will be the reverse of the first half of the digits. Truncate the last digit from the first half of the number, if k is odd.

Algorithm

  • Initialise the numbers n and k.
  • Find the length of the first half of the k-digit palindrome using the value of k.
  • The first half of the palindrome is pow(10, length) + n - 1.
  • If the k is odd, then remove the last digit from the first half of the palindrome.
  • Reverse the first half and print the second half.

Implementation

Following is the implementation of the above algorithm in C++

#include<bits/stdc++.h>
using namespace std;
void findNthPalindrome(int n, int k) {
   int temp = (k & 1) ? (k / 2) : (k / 2 - 1);
   int palindrome = (int)pow(10, temp);
   palindrome += n - 1;
   cout << palindrome;
   if (k & 1) {
      palindrome /= 10;
   }
   while (palindrome) {
      cout << palindrome % 10;
      palindrome /= 10;
   }
      cout << endl;
}
int main(){
   int n = 7, k = 8;
   findNthPalindrome(n ,k);
   return 0;
}

Output

If you run the above code, then you will get the following result.

10066001

Updated on: 22-Oct-2021

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements