数组方法

  1. var isPalindrome = function(x) {
  2. return x.toString() == x.toString().split('').reverse().join('') ? true : false
  3. };

双指针

不需要转成数组类型,字符串可以获取下标,例:const str = ‘hello world’, str[0]即h
Math.floor:向下取整
Math.ceil:向上取整
Math.round:四舍五入

  1. var isPalindrome = function(x) {
  2. const temp = x.toString()
  3. const length = Math.floor(temp.length / 2)
  4. for(let i = 0; i < length; i++){
  5. if(temp[i] !== temp[temp.length - i - 1]) return false
  6. }
  7. return true
  8. };

余数重组

首先判定绝对不符合条件的数字,即负数和末位为0且不为0的数
重组余数,实现数字反转
while先判断,再执行语句块,do…while先执行语句块,再判断

  1. var isPalindrome = function(x) {
  2. if(x < 0 || (x % 10 === 0 && x !== 0)) return false
  3. let temp = 0, s = x
  4. while(s){
  5. temp = temp * 10 + s % 10
  6. s = Math.floor(s /10)
  7. }
  8. return x === temp
  9. };