Palindromes in a given range

Print all the palindromes in the given range of numbers.

Example

Input : {100, 200}
Output : 101, 111, 121, 131, 141, 151, 161,
171, 181, 191

Time complexity : O(n)

Algorithm

For all numbers in the range, check if the number is palindrome or not.

a. If palindrome print it. Increment number by 1

b. Else, increment number by 1.

c. Do this, until number is in the range.

#include <bits/stdc++.h>

using namespace std;

//check if number is palindrome or not
bool isPalindrome(int n)
{
    // Find reverse of n
    int reverse = 0;
    for (int i = n; i > 0; i /= 10)
    {
        reverse = reverse*10 + i;
    }
    if (n == reverse)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// prints palindrome between min and max
void PrintPalindromes(int min, int max)
{
    for (int i = min; i <= max; i++)
    {
        if (isPalindrome(i))
        {
          cout << i << " ";
        }
    }
}
 
//Main function
int main()
{
    PrintPalindromes(1, 600);
    return 0;
}

Try It

 

Translate ยป