algoadvance

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Examples:

Clarifying Questions:

  1. Q: Can the integer be negative?
    • A: Yes, it can be negative, but negative numbers are typically not palindromes.
  2. Q: Can the integer end with zeros?
    • A: Yes, it can, but such numbers are not palindromic.
  3. Q: Do we need to handle large integers?
    • A: The problem should handle the maximum constraints of common integer values in programming.

Strategy:

  1. Negative Numbers: Immediately return False if the number is negative.
  2. Convert to String: Convert the integer to a string and compare it to its reverse.
  3. Return Result: Return whether the string representation is equal to its reverse.

Here’s how the implementation looks:

Code:

def isPalindrome(x: int) -> bool:
    # Negative numbers are not palindromes
    if x < 0:
        return False
    
    # Convert number to string
    str_x = str(x)
    
    # Compare string with its reverse
    return str_x == str_x[::-1]

# Test cases
print(isPalindrome(121))  # Output: True
print(isPalindrome(-121)) # Output: False
print(isPalindrome(10))   # Output: False
print(isPalindrome(0))    # Output: True

Time Complexity:

Thus, the overall time complexity is O(n), where n is the number of digits in the integer.

Try our interview co-pilot at AlgoAdvance.com