Home > Backend Development > C++ > body text

Nth palindrome number among K digits in C++

王林
Release: 2023-09-07 22:25:02
forward
719 people have browsed it

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;
}
Copy after login

Output

If you run the above code, you will get the following results.

10066001
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!