【LeetCode】9. Palindrome Number (2 solutions)

Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

解法一:

求出x的逆序数y,判断两者是否相等即可。

时间复杂度:O(k),k为x的位数

class Solution {
public:
    int reverse(int x) {
        long long y = 0;
        int num = x;

        while(num)
        {
            y = y*10 + num%10;
            num /= 10;
        }
        return y;  //valid
    }
    
    bool isPalindrome(int x) {
        if(x < 0)
            return false;
        if(x == reverse(x))
            return true;
        else
            return false;
    }
};

解法二:

转为string类型,然后首尾指针逐字符比较。

时间复杂度:O(k),k为x的位数

class Solution {
public:
    bool isPalindrome(int x) {
        string xstr = to_string(x);
        for(int i=0, j=xstr.size()-1; i < j; i ++, j --)
        {
            if(xstr[i] != xstr[j])
                return false;
        }
        return true;
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4177082.html