iT邦幫忙

0

Leet Code 3. 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.

翻譯
給一個整數x,如果x是回文整數,則返回true。
例如,121是回文,而123不是。

範例
Input: x = 121
Output: true

Input: x = -121
Output: false
Explanation: 從左到右,它顯示為-121。從右到左,它變為121-。因此,它不是回文。

思路
將x轉為字串並反轉

加深容易混雜的語法
parseInt() 函数:可解析一個字符串,並返回一個整數。
toString() 函数:可把一个 Number 對象轉換為一個字符串,並返回結果

解題

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function (x) {
    return x === parseInt ( x.toString().split('').reverse().join('') )
};

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
koro_michael
iT邦新手 2 級 ‧ 2021-03-04 16:18:48

我記得這一題好像有要求試著不要用字串解

jim55167 iT邦新手 4 級 ‧ 2021-03-06 01:25:39 檢舉

我用google翻譯了它的原文,原文並沒有說明禁止使用字串!
可能題目有更改過吧/images/emoticon/emoticon10.gif

jim55167

也不是說禁止,只是一個小提示

https://ithelp.ithome.com.tw/upload/images/20210306/20135412tCtY6ZaGEL.jpg

我要留言

立即登入留言