Problem

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
  2. Output: true
  1. Input: x = -121
  2. Output: false
  3. Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
  1. Input: x = 10
  2. Output: false
  3. Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
  1. Input: x = -101
  2. Output: false

Solution

  1. 使用双指针的方式,i从前往后遍历,j从后往前遍历

    1. /**
    2. * @param {number} x
    3. * @return {boolean}
    4. */
    5. var isPalindrome = function (x) {
    6. if (x < 0) {
    7. return false;
    8. }
    9. const nums = [];
    10. while(x > 0) {
    11. nums.push(x % 10);
    12. x = parseInt(x / 10);
    13. }
    14. for (let i = 0, j = nums.length - 1; j > i; j--, i++) {
    15. if (nums[j] !== nums[i]) {
    16. return false;
    17. }
    18. }
    19. return true;
    20. };
  2. 只需要判断反转后的数与原数相等,则返回true,否则返回false ```javascript /**

  • @param {number} x
  • @return {boolean} */ var isPalindrome = function (x) { if (x < 0) {

    1. return false;

    } const oriX = x;

    var revertX = 0;

    while(x > 0) {

      revertX = revertX * 10 + x % 10;
      x = parseInt(x / 10);
    

    }

    return revertX === oriX; }; ```