LeetCode Algorithm #9 Palindrome Number

LeetCode Algorithm #9 Palindrome Number

题目内容

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

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.

解题

同样也是比较基础的题目,思考的角度和Reverse Integer比较相似,一个是从数字的角度考虑,一个是处理字符串。

首先考虑一些特殊情况,直接返回false,回节省不少时间。比如负数一定不会为回文数字,能被10整除的也不行,但是0是个例外,所以可以先写下

if(x < 0 || (x % 10 == 0 && x != 0))
    return false;

循环取余

循环取余将整个数字反转过来是一个比较常规的想法,但就像hint中所说的,如果把整个数字反转过来可能出现溢出的情况,则又要进行额外的判断。但是如果只是把一半的数字翻转过来,则不需要判断溢出,需要考虑的则是如果有奇数个数字,两个数字不等长,则要将长的那个除10再进行判断。

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0))
            return false;
        int rev = 0;
        while(x > rev) {
            rev = rev*10 + x%10;
            x /= 10;
        }
        return x == rev || x == rev/10;
    }
};

运行时间不是很稳定,快慢差异比较大,最快的为112ms。

字符串双向判断

也是将数字转成字符串,不过相比Reverse Integer中少了取出再计算的过程,只需要从两头向中间逐个判断前后对应位是否相等,要快不少。

class Solution {
public:
    bool isPalindrome(int x) {
        if(x < 0 || (x % 10 == 0 && x != 0))
            return false;
        char buf[12];
        sprintf(buf, "%d", x);
        int length = strlen(buf);
        for(int i = 0; i < length/2; ++i) {
            if(buf[i] != buf[length-1-i])
                return false;
        }
        return true;
    }
};

运行时间为76ms,超过92.45%。

点赞