9. 回文数
方法一 反转数字 与原数字对比
var isPalindrome = function(x) {
if(x < 0 || (x % 10 == 0 && x!= 0)) return false
let temp = 0, s = x
while(s){
// 例如 12345 % 10 = 5;
temp = temp * 10 + s % 10
// 例如 Math.floor(12345 / 10) = 1234;
s = Math.floor(s/10)
}
return x === temp
};
方法二 双指针 对比左右数字是否相同
2022-03-28,二刷,发现(x % 10 == 0 && x != 0) 为false的话,可以不要
var isPalindrome = function (x) {
const s1 = x.toString();
// 这里注意split()和join() 里面都要用‘’空字符串, 因为默认join()以逗号分割
const s2 = x.toString().split('').reverse().join('');
return s1 == s2;
if (x < 0) {
return false;
}
// cp 意思 copy之前的数
let cp = 0;
let num = x;
while (num) {
const t = num % 10;
num = Math.floor(num / 10);
// 这一步 是cp之前的
cp = cp * 10 + t;
}
return cp === x;
};
var isPalindrome = function(x) {
//if(x < 0 || (x % 10 == 0 && x != 0)) return false
let temp = x.toString()
const n = Math.floor(temp.length/2)
for(let i = 0; i < n; i++){
if(temp[i] != temp[temp.length - i - 1]) return false
}
return true
};
方法三 反转字符串 对比是否相同
var isPalindrome = function(x) {
return x.toString() == x.toString().split('').reverse().join('')
};