Leetcode: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.

 

 

class Solution {

public:

    bool isPalindrome(int x) {

        if (x < 0) return false;

        int div = 1;

        while (x / div >= 10)  div *= 10;

        while (x > 0) {

            int first = x / div;

            int last  = x % 10;

            if (first != last) {

                return false;

            } 

            x = (x % div) / 10;  // eg. 12321 ===> 232

            div /= 100;  

        }

        return true;

    }

};

 

提示中已经说了很清楚了:

1. 当输入为负数时,直接false

2. 如果把数字转为字符数组,然后判断回文,这样就不是O(1)空间复杂度了

3. 如果把数字先反转,然后判断是否相同。可是反转的过程中可能出现溢出的情况

 

这里直接利用回文的定义:我们不断比较 数字的第n位数和倒数第n位数 直到完成比较为止或者中途有不相等的

 

 

 

你可能感兴趣的:(LeetCode)