To find the nth palindrome number with k digits, we can iterate from the first k digit number until we find the nth palindrome number. This method is not efficient. You can try it yourself.
Now, let us see the efficient way to find the nth palindrome number of k digits.
There are two halves in a number. The first half is equal to the reversal of the second half.
The first half of the nth k-digit number is
If k is an odd number, it is (n-1) 10k/2, otherwise it is ( n-1) 10k/2-1
The second half of the nth k-digit number will be the inversion of the first half of the number. If k is an odd number, remove the last digit from the first half of the number.
The 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; }
If you run the above code, you will get the following results.
10066001
The above is the detailed content of Nth palindrome number among K digits in C++. For more information, please follow other related articles on the PHP Chinese website!