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.

 

class Solution {
public:
    bool isPalindrome(int x) {
        int y = 0;
        int tmp = 0;
        int save = x;
        if(x < 0)
            return false;
        while(x)
        {
            tmp = x % 10;
            y = 10 * y + tmp;
            x /= 10;
        }
        if(save == y)
            return true;
        else
            return false;
    }
};
  • 通过把逆转过的数与原来的比较
class Solution {
public:
    bool isPalindrome(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (x < 0)
            return false;
        if (x == 0)
            return true;
            
        int base = 1;
        while(x / base >= 10)
            base *= 10;
            
        while(x)
        {
            int leftDigit = x / base;
            int rightDigit = x % 10;
            if (leftDigit != rightDigit)
                return false;
            
            x -= base * leftDigit;
            base /= 100;
            x /= 10;
        }
        
        return true;
    }
};
  • 先得到base;大小为x的最大位数
  • 然后每次把第一位和末尾比较
  • 这种方法和上面的比,并没有速度上的优势
posted @ 2015-10-29 13:41  dylqt  阅读(126)  评论(0编辑  收藏  举报