N’th palindrome of K digits in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the n-th palindrome of k digits.

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.

Example

Let's see the code.

 Live Demo

#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
raja
Published on 29-Jun-2021 09:40:19
Advertisements