Skip to content

9. Palindrome Number

难度: Easy

刷题内容

原题连接

  • https://leetcode.com/problems/palindrome-number

内容描述

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?

解题方案

思路 1 **- 时间复杂度: O(log2 N)*- 空间复杂度: O(1)***

  • 不使用字符串,使用除法分别从首尾获得数字,最后对比是否相同

代码:

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    if(x<0||x!==0&&x%10===0)
        return false;
    var reverse = 0;
    while (x>reverse){
        reverse = reverse*10 +x%10;
        x = Math.floor(x/10);
    }
    return reverse === x||Math.floor(reverse/10) === x;
};

思路 2 **- 时间复杂度: O(N)*- 空间复杂度: O(N)***

  • 转化为字符串,reverse字符串

代码:

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

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组