LeetCode EP.5
9. Palindrome Number
Published in
2 min readJun 21, 2022
Given an integer
x
, returntrue
ifx
is palindrome integer.An integer is a palindrome when it reads the same backward as forward.
For example,
121
is a palindrome while123
is not.
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
Follow up: Could you solve it without converting the integer to a string?
思路
這裡我一開始預想是用前後輪巡的方式,所以直接把 List size/2 所以得到下面 Answer 1 的解法,Else 會這樣寫是因為 Submit 時發現 testcase 裡 0 算是回文的。
這裡算是第一次解,但後來 Submit 後發現大家 Runtime 怎麼都這麼低,去看了一下別人的寫法,發現有個更優秀的直接使用 reversed 就好了。
那如果想玩玩看的話也可以參考我的 Github 使用 IntelliJ 就可以 Build 了,裡面也寫了 Test 來驗證。