[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.

思考:提示说"Reverse Integer" might overflow,作为此题不必考虑,因为回环数翻转后还是它本身,既然原来没有溢出,翻转后也不会溢出。

class Solution {
public:
    bool isPalindrome(int x) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		if(x<0) return false;
		int m=x;
		int n=0;
		while(m)
		{
			n=n*10+m%10;
			m=m/10;
		}
		if(n==x) return true;
		else return false;
    }
};

  在这里http://www.cnblogs.com/remlostime/archive/2012/11/14/2770624.html发现了一个更好的办法。每次,取出数的最高位和最低位比较,设置一个base为10^n,用来取出数的最高位,每次循环除以100,因为每次数会消去2位。

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;
    }
};

  

posted @ 2013-11-07 16:24  七年之后  阅读(202)  评论(0编辑  收藏  举报