Palindrome Number - LeetCode

김견지·2025년 3월 11일

LeetCode

목록 보기
2/13
post-thumbnail

Sumbmission Link

Question

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.

Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Constraints:
-231 <= x <= 231 - 1

My Solutioin

Code

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        else:
            str_x = list(str(x))
            for i, ch in enumerate(str_x):
                if str_x[-1 * (i + 1)] != ch:
                    return False
            return True

I divided it for two cases.

  1. If it is negative, it can't be palindrome.
  2. If it is positive, I should check from the first digit.

And we need to check only half of the whole digits.

Feedback

Python Grammar

str()

OMG🤦‍♀️.. I forgot how to change int to string that I used string() at first.

a = 123  # int
str_a = str(a)  # string '123'

b = 12.3 # float
str_b = str(b)  # string '12.3'

# also possible to use
str_a = f"{a}"

Better Solution?

Fastest Sol.

class Solution:
    def isPalindrome(self, x: int) -> bool:
    	# literally comparing with reversed x,
        # which is definition of palindrome!
        return str(x)==str(x)[::-1]

Comment

I have to know how to use basic grammar of python (like index) more.

profile
ML Engineer / Autonomous driving

0개의 댓글