Find all numbers less than n, which are palindromic. Numbers can be printed in any order.
Input : n = 12 Output : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11 Input : n = 104 Output : 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101 [Note that below program prints these numbers in different order]
Brute Force: We check all the numbers from 1 to n whether its decimal representation is palindrome or not.
Efficient Approach: We start from 1 and create palindromes of odd digit and even digits up to n. For every number (starting from 1), we append its reverse at end if we need even length palindrome numbers. For odd length palindrome, we append reverse of all digits except last one.
11 22 33 44 55 66 77 88 99 1 2 3 4 5 6 7 8 9 101
Note that the above program doesn’t print output in sorted order. To print in sorted order, we can store palindromes in a vector and store it.
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Palindromic Selfie Numbers
- Sum of all odd length palindromic numbers within the range [L, R]
- Algorithm to generate positive rational numbers
- An Interesting Method to Generate Binary Numbers from 1 to n
- New Algorithm to Generate Prime Numbers from 1 to Nth Number
- Make palindromic string non-palindromic by rearranging its letters
- Generate a list of n consecutive composite numbers (An interesting method)
- Generate k digit numbers with digits in strictly increasing order
- Longest Palindromic Substring using Palindromic Tree | Set 3
- C++ program to find all numbers less than n, which are palindromic in base 10 and base 2.
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Palindromic Primes
- Lexicographically first palindromic string
- Longest Palindromic Substring | Set 1
- Longest Palindromic Subsequence | DP-12