[LeetCode] Palindrome Number

黃馨平
Jackycsie
Published in
2 min readSep 9, 2020

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

Example 1:

Input: 121
Output: true

Example 2:

Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

解題思路:

首先我們可以知道只要是負的就可以傳 false ,接著判斷字串是基數偶數,如果是偶數直接對半切,拿第一個比對最後一個,依此類推,如果是基數,直接忽略最中間的那個。若是中間任何一個只要不同就直接傳 false 。這樣最佳時間複雜度是 O(1),最差則是 O(n/2)。

  • Runtime: 48 ms, faster than 86.46%
  • Memory Usage: 12.8 MB, less than 43.23%

解題思路二:

將字串反轉後,跟原本的數字做比對,但這樣的時間複雜度一定是 O(n),不是非常聰明的作法。

  • Runtime: 52 ms, faster than 79.30%
  • Memory Usage: 12.7 MB, less than 80.05%

--

--

黃馨平
Jackycsie

閱讀本是尋常事,繁華靜處遇知音