Palindrome Number Solution || How to Check if an Integer is a Palindrome using Python || Detecting Palindromic Numbers with Python ||

Palindrome Number:

Given an integer x, return true if x is a palindrome and false otherwise.

Example 1:

Input: x = 121

Output: true

Explanation: 121 reads as 121 from left to right and from right to left.


Example 2:

Input: x = -121

Output: false

Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.


Sample input

121


Sample output

true




Program:

def is_palindrome(x):

    # Convert the number into a string

    str_x = str(x)

    # Check if the string is equal to its reverse

    return str_x == str_x[::-1]


# Taking input from the user

x = int(input())


result = is_palindrome(x)

if result:

    print("true")

else:

    print("false")








Explanation:

Function Definition:
A function named is_palindrome is introduced, which takes an integer x as an argument.

Conversion to String:
Inside the function, the integer x is transformed into a string. This conversion makes it easier to check for palindrome properties.

Palindrome Check:
1)The function examines if the string representation of the number is the same when read backwards.
2)This is accomplished by using slicing to reverse the string (str_x[::-1]) and then comparing it to the original.
3)If they match, the function returns True, indicating the number is a palindrome. Otherwise, it returns False.

User Input:
1)The user is prompted to input a number.
2)The input() function fetches input as a string, so the program converts this string to an integer using int().

Determine Palindrome Status:
1)The previously defined is_palindrome function is invoked with the user's number.
2)The result (a boolean) is stored in the result variable.

Output the Result:
1)Based on the result, the program prints the outcome.
2)If the result is True, "true" is printed.
3)If the result is False, "false" is printed.

Post a Comment

0 Comments