LeetCode Solution, Easy, 9. Palindrome Number

回文數值

The link is below and you could see the description. I will use several languages to solve this problem and explain how to solve the problem. Loading... Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared…leetcode.com

JavaScript

/**
 * [@param](http://twitter.com/param) {number} x
 * [@return](http://twitter.com/return) {boolean}
 */
var isPalindrome = function(x) {
  if (x < 0) return false;
  const xS = x.toString();
  if (xS.length === 1) return true;

  let i = xS.length - 1;
  let k = 0;
  while (i > k) {
    if (xS[i] !== xS[k]) return false;
    i--;
    k++;
  }

  return true;
};

Step 1: 先略過不符合條件的數值,例如只有個位數和負值

Step 2: 將數字轉成字串,並儲存字串的長度 i ,然後使用迴圈使用從兩頭開始內縮判斷是否相同(忘記這演算法叫什麼了)。如果一有不同的就回傳 false 。最後回傳結束都沒有回傳就最後回傳 true ,代表符合條件

Python3

class Solution:
    def isPalindrome(self, x: int) -> bool:
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        elif x >= 10:
            return str(x)[::-1] == str(x)
        else:
            return True

這邊就可以看到有如第七題提到的一樣,Python 對於字串有很方便地偷吃步方法,可以直接反轉字串的順序。

Go

func isPalindrome(x int) bool {
  if x < 0 || x%10 == 0 && x != 0 {
    return false
  }

  result := 0
  for c := x; c > 0; {
    result = result*10 + c%10
    c /= 10
  }

  return result == x
}

Go 這邊的解法是有點類似第七題的解題方式,但是為什麼不使用類似 JavaScript 的解題方式呢?因為跑出來這種方式的執行速度比較快,可能因為使用類似 JavaScript 的解題方式的話我會使用到外部套件的關係吧。不過我在下面也會附上使用 JavaScript 解題邏輯的寫法:

import "strconv"

func isPalindrome(x int) bool {
  if x < 0 {
    return false
  }

  s := strconv.Itoa(x)
  for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    if s[i] != s[j] {
      return false
    }
  }

  return true
}

Did you find this article valuable?

Support 攻城獅 by becoming a sponsor. Any amount is appreciated!