My experience of solving algorithmic problem of checking whether the number is a palindrome or not.

A photo of Betizazu Alemu looking professional.
Betizazu Alemu
  • 2 min read

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 = 121

Output: true

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

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.

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:

  1. Create a variable to hold the copy of the number
  2. Create a remainder variable and initialize it by zero
  3. Perform a division of the number by 10
  4. Multiply the remainder by 10 and add the remainder of the above division
  5. Update the number by the integer part of the above division
  6. Keep on performing the above three steps until the number becomes zero
  7. 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.

python
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 == x

Using builtin function to perfomr string reverse.

python
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])

Discover related blog posts that delve into similar themes, share valuable insights, and offer fresh perspectives.