palindrome number -Python
2024
Steps to Reverse a Number:
- Use
% 10
to get the last digit of the number. - Use
// 10
to remove the last digit from the number. - Build the reversed number digit by digit.
Here’s the code to check if a number is the same when reversed:
def is_palindrome(number):
original_number = number
reversed_number = 0
while number > 0:
last_digit = number % 10 # Get the last digit
reversed_number = reversed_number * 10 + last_digit # Build the reversed number
number = number // 10 # Remove the last digit
return original_number == reversed_number
# Test the function
x = 121
if is_palindrome(x):
print(f"{x} is a palindrome!")
else:
print(f"{x} is not a palindrome!")