LeetCode热题(JS版)- 9. 回文数

94 阅读1分钟

题目

给定整数 x, 判断是否是回文数

示例 1:

输入: x = 121
输出: true
说明: 121从左到右和从右到左读作121。

示例 2:

输入: x = -121
输出: false
说明: 从左到右,它是-121。从右到左,它是121-。因此,它不是回文。

示例 3:

输入: x = 10
输出: false
说明: 从右向左读取01。因此,它不是回文。

思路

function isPalindrome(x: number): boolean {
  // 负数返回
  if (x < 0) return false;

  // 取出每一位
  const numbers = [];
  while (x) {
    numbers.push(x % 10);
    x = Math.floor(x / 10);
  }

  // 从头到尾判断是否相同
  let i = 0;
  const { length } = numbers;
  const half = Math.ceil(length / 2);
  let flag = true;
  while (i <= half) {
    if (numbers[i] !== numbers[length - 1 - i]) {
      flag = false;
      break;
    }
    i++;
  }

  return flag;
}

image.png