Print Palindrome Numbers in Given Range using Python

There are some numbers in mathematics when even reversed remain the same. Well as for observing these numbers with human eyes we don’t need to exert too much stress on our brains. However, to find the same thing using a computer program is quite a challenge for newbie programmers. Such numbers when even reversed remain the same are known as Palindrome numbers. And in today’s article, we’ll try to find Palindrome numbers using programs. So let’s find out how to print Palindrome Numbers in Given Range using Python.

So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a somewhat hard question you might get asked in an interview so make sure to practice it on your own after reading this article.

 

What’s The Approach?

 

  • Let’s consider input number min till range max Therefore if the reverse of min is similar to min we’ll print true otherwise we’ll print false.

 

  • We will create a separate function isPalindrome to return the reverse of input min.

 

  • Create a reverse variable rev, we will multiply it by 10 & perform a modulo operation with 10

 

  • If the function returns 1 then we’ll print the number, otherwise, we’ll pass.

 

  • The above instructions will keep executing till we reach the end of the input range. So we’ll create a for loop, starting and ending with our given range incremented by 1 each time.

 

Also Read: Multiply Integers Using Russian Peasant Algorithm in C++

 

Python Program To Print Palindrome Numbers in Given Range

 

Input:

100, 200

 

Output:

101 111 121 131 141 151 161 171 181 191 

 

# 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, 200)

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *