Given a integer k, find the sum of first k even-length palindrome numbers.
Even length here refers to the number of digits of a number is even.
Input : k = 3 Output : 66 Explanation: 11 + 22 + 33 = 66 (Sum of first three even-length palindrome numbers) Input : 10 Output : 1496 Explanation: 11+22+33+44+55+66+77+88+ 99+1001 = 1496
A naive approach will be to check every even length number, if it is a palindrome number then we sum it up. We repeat the same process for first K even length palindrome numbers and sum them up to get the sum.
In this case complexity will go high as even length numbers are from 10-99 and then 1000-9999 and then so on…
10-99, 1000-9999, 100000-999999.. has 9, 90, 900 respectively palindrome numbers in them, so to check k numbers we have to check a lot of numbers which will not be efficient enough.
An efficient approach will be to observe a pattern for even length prime numbers.
11, 22, 33, 44, 55, 66, 77, 88, 99, 1001, 1111, 1221, 1331, 1441, 1551, 1661…
1st number is 11, 2nd is 22, third is 33, 16th is 16-rev(16) i.e., 1661.
So the Nth number will int(string(n)+rev(string(n)).
See here for conversion of integer to string and string to integer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
- Count all palindrome which is square of a palindrome
- Sum of all palindrome numbers present in an Array
- Sum of all N digit palindrome numbers
- Sum of all Palindrome Numbers present in a Linked list
- Given two strings check which string makes a palindrome first
- Next word that does not contain a palindrome and has characters from first k
- Find the player who rearranges the characters to get a palindrome string first
- Count the number of digits of palindrome numbers in an array
- Count of N-digit Palindrome numbers
- Find all palindrome numbers of given digits
- Largest palindrome which is product of two N-digit numbers : Set 2
- Check if the sum of digits of N is palindrome
- Check if sum of any subarray is Palindrome or not
- Function to check if a singly linked list is palindrome
- Palindrome Partitioning | DP-17
- Given a number, find the next smallest palindrome
- Check if a number is Palindrome
- Minimum insertions to form a palindrome | DP-28
- Check if a given string is a rotation of a palindrome
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.