这是我参与8月更文挑战的第9天,活动详情查看:8月更文挑战
leetcode-cn站点挂了,用原站吧。
题目
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
Follow up: Could you solve it without converting the integer to a string?
解题思路
思路1
Use a varibale to reverse number then check with given number
var isPalindrome = function(x) {
if (x < 0) return false
let rev = 0
for(let i = x; i >= 1; i = Math.floor(i/10)) rev = rev*10 + i%10
return rev === x
};
思路2
var isPalindrome = function(x) {
const arr = String(x).split('');
while (arr.length > 1) {
if (arr.shift() !== arr.pop()) {
return false;
}
}
return true;
};
思路3
var isPalindrome = function(x) {
if (x < 0) return false;
// reverse the string representation of x
const reverse = `${x}`.split('').reverse().join('');
// compare the value regardless of types
return x == reverse;
};
最后
曾梦想仗剑走天涯
看一看世界的繁华
年少的心总有些轻狂
终究不过是个普通人
无怨无悔我走我路
「前端刷题」No.9