Leetcode Exercise 3
Palindrome Number
Published in
2 min readNov 22, 2018
Description
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#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.#3
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
構思
- 先判斷是否小於0,若小於0,直接回傳false
- 將數字轉成string
- 和該string反轉做比較,並回傳結果
實作程式碼
# @param {Integer} x
# @return {Boolean}
def is_palindrome(x)
if x < 0
return false
else
x = x.to_s
return x == x.reverse
end
end
Returns a string containing the place-value representation of
int
with radixbase
(between 2 and 36).
Returns a new string with the characters from str in reverse order.
結果
beats 100.00% 😀