
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- n-th number whose sum of digits is ten in C++
- Find k-th smallest element in given n ranges in C++
- Find the k-th smallest divisor of a natural number N in C++
- The k-th Lexicographical String of All Happy Strings of Length n in C++
- Find M-th number whose repeated sum of digits of a number is N in C++
- Print first k digits of 1/n where n is a positive integer in C Program
- n-th number with digits in {0, 1, 2, 3, 4, 5} in C++
- Find the fractional (or n/k – th) node in linked list in C++
- Finding n-th number made of prime digits (2, 3, 5 and 7) only in C++
- Construct K Palindrome Strings in C++
- Find n-th element in a series with only 2 digits (and 7) allowed in C++
- Palindrome Partitioning\n
- Remove K Digits in C++
- K-th Symbol in Grammar in C++
- K-th Element of Two Sorted Arrays in C++
