1
0

初めに

前回に続き,LeetCodeの解答と解説をまとめていこうと思います~~

LeetCode(Palindrome Number)

Given an integer x, return true if x is a
palindrome, and false otherwise.

凄くシンプルな問題ですね.
これは「回文ならTrueを返してね.そうでなければFalseでお願い」ということですね.
じゃあ,さっそく解いてみましょう~

#解答・解説

  def isPalindrome(self, x: int) -> bool:
         x_str = str(x)

         x_str_reversed = x_str[::-1]

         if x_str == x_str_reversed:
             return True
         else:
             return False

これは一瞬で書けますね!
与えられた数字を文字列として置き換えて,反転させたものをx_str_reversedに代入する.
後はそれを比較して,一致していればTrueを一致していなければFalseを返せば終了です!

ちなみに,x_str_reversed = x_str[::-1]は文字列全体を-1のステップでスライスすることで逆順にしています.
逆順にする方法としては,今回使用したスライスに加え,reverse,reversed,ループ文がありますが好きなものを使えばよいと思います.
速度はreverseが一番速いという実験結果が出ているようですのでそちらを使うとleetcodeの実行結果の時間が短縮されるかもしれません.
ちなみに,このコードは58msです.

それでは,また次回お会いしましょう~~

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0