Technical Roadmap

Python Program to check if a number is Palindrome

Before making a program, let's understand what a Palindrome number is.

The Logicoria Tip

Think of a Palindrome like a Mirror. If the number looks at itself in the mirror and sees the exact same reflection, it’s a Palindrome. Like 121, and if I reverse it, it is still 121!

Palindrome Number:

A number is a palindrome if it is the same or equal even if we reverse the place of its digits.

To find a palindrome number:

  • 1. If you take a number and reverse it and it is still the same, it is a palindrome.
  • 2. 121 is a Palindrome Number as it is the same even when reversed.

Algorithm to check for Palindrome:

  • First, make a variable and store a number in it.
  • Make another variable and store the first number in it.
  • Now we will reverse the second number and check if both the original and reversed no are equal. If it is the same, it is a palindrome number. Otherwise not.

Before reversing, u need to know how to reverse a number:

PYTHON
# Program to check if a number is a palindrome
num = int(input("Enter a number: "))
temp = num
reverse_num = 0

while temp > 0:
    remainder = temp % 10
    reverse_num = (reverse_num * 10) + remainder
    temp = temp // 10

if num == reverse_num:
    print(num, "is a Palindrome")
else:
    print(num, "is NOT a Palindrome")

Output

Enter a number: 121
121 is a Palindrome

Explanation

  • First, we made a variable num = 121 and then we copied it into another variable temp to compare both numbers at the end. As we cannot reverse the actual number (because the loop would turn it into zero), we need a copy of it to reverse.
  • Then we made a variable reverse_num and set its initial value to 0.
  • We use a while loop because we don't know in how many iterations we will get the number reversed, as it can be a 3, 4, or 6-digit number. So until temp is greater than 0, our loop will continue. Inside the loop, we declare a variable remainder to save the last digit using modulo.
  • In the next line, we made a variable reverse_num = reverse_num * 10 + remainder. In the next iteration, we will get the second-to-last digit which will then add to the previous reverse_num * 10. This will continue until we get temp = 0, as in the next line we are using floor division to get the quotient.