Home  >  Article  >  Backend Development  >  Nth palindrome number among K digits in C++

Nth palindrome number among K digits in C++

王林
王林forward
2023-09-07 22:25:02680browse

Nth palindrome number among K digits in C++

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.

Algorithm

  • Initialize the numbers n and k.
  • Use the value of k to find the length of the first half of the k-digit palindrome number.
  • The first half of the palindrome number is pow(10, length) n - 1.
  • If k is an odd number, remove the last digit from the first half of the palindrome number.
  • Reverse the first half and print the second half.

Implementation

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;
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete