Home » Interview Questions » String Interview Questions » Palindromes in a given range

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

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Find the Closest Palindrome number
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions