Problem description
Check if a number is Palindrome Number.
Given an integer x, return true if x is a palindrome, and false otherwise.
Examples
Input:
x = 121Output:
trueExplanation:
121reads as121from left to right and from right to left.
Input:
x = -121Output: false
Explanation: From left to right, it reads
-121. From right to left, it becomes121-. Therefore it is not a palindrome.
You can find a brief description about the problem here.
Experience
My intuition is simple. First, check if a number is a negative number and if the number is negative, return false since there is no reverse for it.
When the number is greater than zero, I will follow the following steps:
- Create a variable to hold the copy of the number
- Create a remainder variable and initialize it by zero
- Perform a division of the number by 10
- Multiply the remainder by 10 and add the remainder of the above division
- Update the number by the integer part of the above division
- Keep on performing the above three steps until the number becomes zero
- Then check if the value of the remaining variable equals the copy of the number
The results
- Runtime: 66 ms, faster than 91.10% of Python3 online submissions for Palindrome Number problem.
- Memory Usage: 14 MB, less than 59.42% of Python3 online submissions for Palindrome Number problem.
The code
Without using any buildint function.
def isPalindrome(self, x: int) -> bool:
	reverse = 0
	x_copy = x
	
	if x > 0:
		while x_copy:
			reverse = (reverse * 10) + (x_copy % 10)
			x_copy //= 10
			
	return reverse == xUsing builtin function to perfomr string reverse.
def isPalindrome(self, x: int) -> bool:
	if x < 0: return False
	# first convert it to string, then reverse it, and convert it back to int
	# then compare it with the actual value
	return x == int(str(x)[::-1]) 
  
 