Open In App

Program to print all palindromes in a given range

Improve
Improve
Like Article
Like
Save
Share
Report

Given a range of numbers, print all palindromes in the given range. For example if the given range is {10, 115}, then output should be {11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111}
We can run a loop from min to max and check every number for palindrome. If the number is a palindrome, we can simply print it. 

Implementation:

C++




#include<iostream>
using namespace std;
 
// A function to check if n is palindrome
int isPalindrome(int n)
{
    // Find reverse of n
    int rev = 0;
    for (int i = n; i > 0; i /= 10)
        rev = rev*10 + i%10;
 
    // If n and rev are same, then n is palindrome
    return (n==rev);
}
 
// prints palindrome between min and max
void countPal(int min, int max)
{
    for (int i = min; i <= max; i++)
        if (isPalindrome(i))
          cout << i << " ";
}
 
// Driver program to test above function
int main()
{
    countPal(100, 2000);
    return 0;
}


Java




// Java Program to print all
// palindromes in a given range
 
class GFG
{
     
    // A function to check
    // if n is palindrome
    static int isPalindrome(int n)
    {
         
        // Find reverse of n
        int rev = 0;
        for (int i = n; i > 0; i /= 10)
            rev = rev * 10 + i % 10;
             
        // If n and rev are same,
        // then n is palindrome
        return(n == rev) ? 1 : 0;
    }
     
    // prints palindrome between
    // min and max
    static void countPal(int min, int max)
    {
        for (int i = min; i <= max; i++)
            if (isPalindrome(i)==1)
                System.out.print(i + " ");
    }
     
    // Driver Code
    public static void main(String args[])
    {
        countPal(100, 2000);
    }
}
 
// This code is contributed by Taritra Saha.


Python3




# Python3 implementation of above idea
 
# A function to check if n is palindrome
def isPalindrome(n: int) -> bool:
 
    # Find reverse of n
    rev = 0
    i = n
    while i > 0:
        rev = rev * 10 + i % 10
        i //= 10
 
    # If n and rev are same,
    # then n is palindrome
    return (n == rev)
 
# prints palindrome between min and max
def countPal(minn: int, maxx: int) -> None:
    for i in range(minn, maxx + 1):
        if isPalindrome(i):
            print(i, end = " ")
 
# Driver Code
if __name__ == "__main__":
    countPal(100, 2000)
 
# This code is contributed by
# sanjeev2552


C#




// C# Program to print all
// palindromes in a given range
using System;
 
class GFG
{
 
// A function to check
// if n is palindrome
public static int isPalindrome(int n)
{
 
    // Find reverse of n
    int rev = 0;
    for (int i = n; i > 0; i /= 10)
    {
        rev = rev * 10 + i % 10;
    }
 
    // If n and rev are same,
    // then n is palindrome
    return (n == rev) ? 1 : 0;
}
 
// prints palindrome between
// min and max
public static void countPal(int min,
                            int max)
{
    for (int i = min; i <= max; i++)
    {
        if (isPalindrome(i) == 1)
        {
            Console.Write(i + " ");
        }
    }
}
 
// Driver Code
public static void Main(string[] args)
{
    countPal(100, 2000);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
// A function to check if n is palindrome
function isPalindrome(n)
{
    // Find reverse of n
    var rev = 0;
    for (var i = n; Math.trunc(i) > 0; i /= 10)
    {
        rev = ((rev*10) + (Math.trunc(i)%10));
         
        }
   
    // If n and rev are same, then n is palindrome
    return (n==rev);
}
     
 
// prints palindrome between min and max
function countPal(min,  max)
{
    for (var i = min; i <=max; i++)
    {
        if(isPalindrome(i))
        document.write(i+" " );
       }
}
 
// Driver program to test above function
 
    countPal(100, 2000);
</script>


Output

101 111 121 131 141 151 161 171 181 191 202 212 222 232 242
 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404 
 414 424 434 444 454 464 474 484 494 505 515 525 535 545 555 565 
 575 585 595 606 616 626 636 646 656 666 676 686 696 707 717 727 
 737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888
 898 909 919 929 939 949 959 969 979 989 999 1001 1111 1221 1331 
 1441 1551 1661 1771 1881 1991 





Time Complexity:

Time complexity of function to check if a number N is palindrome or not is O(logN).

We are calling this function each time while iterating from min to max.

So the time complexity will be O(Dlog(M)).

Where,

D= max-min

M = max

Auxiliary Space: O(1)

Approach#2: Using filter

This approach defines a function is_palindrome that checks if a given number is a palindrome. It then defines a function palindrome_range that takes a range of numbers and returns a list of all palindromic numbers in that range using a combination of the range, filter, and list functions.

Algorithm

1. Define a function that takes two integer arguments as the range of numbers to check for palindromes.
2. Create a list of all integers in the range.
3. Use map and lambda to filter the list to only include palindromes.
4. Return the list of palindromes.

C++




#include <iostream>
#include <sstream>
#include <vector>
 
// Function to check if a number is a palindrome
bool isPalindrome(int num)
{
    // Convert integer to string and compare it with its
    // reverse to check for palindrome
    std::string numStr = std::to_string(num);
    return numStr
           == std::string(numStr.rbegin(), numStr.rend());
}
 
// Function to find palindromes in a given range
std::vector<int> palindromeRange(int start, int end)
{
    // Create a vector of numbers in the specified range
    std::vector<int> nums;
    for (int i = start; i <= end; i++) {
        nums.push_back(i);
    }
 
    // Vector to store palindromes found in the range
    std::vector<int> palindromes;
    for (int x : nums) {
        // Check if the number is a palindrome and add it to
        // the palindromes vector
        if (isPalindrome(x)) {
            palindromes.push_back(x);
        }
    }
 
    return palindromes;
}
 
// Main method
int main()
{
    int start = 100;
    int end = 2000;
 
    // Find palindromes in the given range and print the
    // result
    std::vector<int> result = palindromeRange(start, end);
 
    // Print the result
    std::cout << "[";
    for (size_t i = 0; i < result.size(); ++i) {
        std::cout << result[i];
        if (i < result.size() - 1) {
            std::cout << ", ";
        }
    }
    std::cout << "]" << std::endl;
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
    // Function to check if a number is a palindrome
    static boolean isPalindrome(int num) {
        // Convert integer to string and compare it with its reverse to check for palindrome
        String numStr = Integer.toString(num);
        return numStr.equals(new StringBuilder(numStr).reverse().toString());
    }
 
    // Function to find palindromes in a given range
    static List<Integer> palindromeRange(int start, int end) {
        // Create a list of numbers in the specified range
        List<Integer> nums = new ArrayList<>();
        for (int i = start; i <= end; i++) {
            nums.add(i);
        }
 
        // List to store palindromes found in the range
        List<Integer> palindromes = new ArrayList<>();
        for (int x : nums) {
            // Check if the number is a palindrome and add it to the palindromes list
            if (isPalindrome(x)) {
                palindromes.add(x);
            }
        }
 
        return palindromes;
    }
 
    // Main method
    public static void main(String[] args) {
        int start = 100;
        int end = 2000;
 
        // Find palindromes in the given range and print the result
        List<Integer> result = palindromeRange(start, end);
        System.out.println(result);
    }
}


Python3




def is_palindrome(num):
    return str(num) == str(num)[::-1]
 
def palindrome_range(start, end):
    nums = list(range(start, end+1))
    palindromes = list(filter(lambda x: is_palindrome(x), nums))
    return palindromes
 
start=100
end=2000
print(palindrome_range(start, end))


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
    // Function to check if a number is a palindrome
    static bool IsPalindrome(int num)
    {
        // Convert integer to string and compare it with its
        // reverse to check for palindrome
        string numStr = num.ToString();
        return numStr
            == new string(numStr.Reverse().ToArray());
    }
 
    // Function to find palindromes in a given range
    static List<int> PalindromeRange(int start, int end)
    {
        // Create a list of numbers in the specified range
        List<int> nums
            = Enumerable.Range(start, end - start + 1)
                  .ToList();
 
        // List to store palindromes found in the range
        List<int> palindromes = new List<int>();
        foreach(int x in nums)
        {
            // Check if the number is a palindrome and add
            // it to the palindromes list
            if (IsPalindrome(x)) {
                palindromes.Add(x);
            }
        }
 
        return palindromes;
    }
 
    // Main method
    static void Main()
    {
        int start = 100;
        int end = 2000;
 
        // Find palindromes in the given range and print the
        // result
        List<int> result = PalindromeRange(start, end);
 
        // Print the result
        Console.Write("[");
        for (int i = 0; i < result.Count; ++i) {
            Console.Write(result[i]);
            if (i < result.Count - 1) {
                Console.Write(", ");
            }
        }
        Console.WriteLine("]");
    }
}


Javascript




// This function checks whether a given number is a palindrome or not
function is_palindrome(num) {
    return String(num) === String(num).split("").reverse().join("");
}
 
// This function returns a list of all palindrome numbers within a given range
function palindrome_range(start, end) {
    let nums = Array.from({length: (end - start) + 1}, (_, i) => i + start);
    let palindromes = nums.filter(num => is_palindrome(num));
    return palindromes;
}
 
// Example usage
let start = 100;
let end = 2000;
console.log(palindrome_range(start, end));


Output

[101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, 525, 535, 545, 555, 565, 575, 585, 595, 606, 616, 626, 636, 646, 656, 666, 676, 686, 696, 707, 717, 727, 737, 747, 757, 767, 777, 787, 797, 808, 818, 828, 838, 848, 858, 868, 878, 888, 898, 909, 919, 929, 939, 949, 959, 969, 979, 989, 999, 1001, 1111, 1221, 1331, 1441, 1551, 1661, 1771, 1881, 1991]





Time complexity: O(n*k), where n is the number of integers in the range and k is the length of the largest integer in the range.

Auxiliary Space: O(m), where m is the number of palindromes in the range



Last Updated : 04 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads