leetcode : Palindrome Number
こんにちは。かずとよです。
今回は、Palindrome Numberという問題を解きました。
問題は以下。
Given an integer x
, return true
if x
is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121
is palindrome while 123
is not.
Example 1:
Input: x = 121 Output: true
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.
Example 4:
Input: x = -101 Output: false
Constraints:
-231 <= x <= 231 - 1
翻訳+自分なりの解釈は以下。
【整数xが回文整数なら、true。違うならfalseと返す。
回文整数とは、前からでも後ろからでも同じ数値になる整数のこと。
121は回文整数で、123はそうではない。】
さらに例文2の文章
【このパターンは、前から読むと-121。後ろから読むと121-となる。
よって、回文整数ではない。】
ふむ・・・なるほど。
ということは、負の数は全て回文整数ではないということ。
ならば、これでどうじゃい!!
def is_palindrome(x) if x >= 0 # xが0以上なら(正の数、もしくは0) x_reverse_s = x.to_s.reverse # 一旦xを文字列にして、反転。 x_reverse = x_reverse_s.to_i # 数値に変換 if x == x_reverse # ここで再度条件分岐。xと反転したもの(x_reverse)が同じなら return true else return false end else # そもそも負の数なら return false end end
クリアできました。
今回は、意外とあっさりいけました。
知ってることだけで解けたので、web検索もなしでした。翻訳以外。
(そもそもfalseと返す記述をしてなかったり、0をfalseで返してしまったりといったミスはありましたが)
*今回の学び:
- 回文整数とは、前から読んでも後ろから読んでも同じ数字になるもの。負の数は-がある時点で回文整数になり得ない。
- 0も回文整数である。