反转字符串
var isPalindrome = function(x) {
return x +''== (x+'').split('').reverse().join('')
};
从两端起比较字符串
var isPalindrome = function(x) {
let y = x.toString()
let i = 0;
for (let i = 0; i < (y.length / 2); ++i) {
let j = y.length - 1 - i;
if (y[i] != y[j]) {
return false;
}
}
return true;
};
反转数字
const isPalindrome = x => {
let revX = 0;
let tmp = x;
while (0 < tmp) {
revX = revX * 10 + (tmp % 10);
tmp = Math.trunc(tmp / 10);
}
return revX === x;
};
从两端起比较数字的每一位
var isPalindrome = function(x) {
if (x < 0) { // -1
return false
}else if (x < 10) { // 0~ 9
return true
}else if (x % 10 === 0) {//10,20, 100, 3000
return false
}else {
var digit = ~~Math.log10(x) + 1 //求出它有多少数
var highDivisor = Math.pow(10, digit-1) //最高位数的除数(目的是得到最高位)
for(var i = 0; i < digit /2; i++ ){
if(Math.floor(x / highDivisor ) !== x % 10){
return false
}
x = x % highDivisor; //去掉最高位 1234 --> 234
x = Math.floor(x / 10 ); //去掉最低位 234 --> 23
highDivisor = highDivisor /100
}
return true
}
};