【Leet Code】Palindrome Number

Palindrome Number

 Total Accepted: 19369 Total Submissions: 66673My Submissions

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


推断一个数整数是不是回文?比如121,1221就是回文,好吧,直接利用前面写过的【Leet Code】Reverse Integer——“%”你真的懂吗?

只是这里要考虑翻转后,数值溢出的问题,代码例如以下:

/* 
//first method 
class Solution {
public:
    bool isPalindrome(int x) 
    {
        long long temp = x;
        long long  ret = 0;  
        bool isNegative = false;  
        if (temp < 0)   
        {  
            return false;  
        }  
        while (temp)   
        {  
            ret = ret * 10 + temp % 10;  
            temp /= 10;  
        }  
        if(x == ret)
        {
            return true;
        }
        else
        {
            return false;
        }
        
    }
};
*/

当然,我们还有更好的方法,事实上,初见这个题目,第一个想法是取头取尾进行比較,然后把头尾去掉,再循环,直到数值为个位数为止:

class Solution {
public:
    bool isPalindrome(int x) 
    {
        if (x < 0) 
        {
            return false;
        }
        int divisor = 1;
        while (x / divisor >= 10) 
        {
            divisor *= 10;
        }
        while (x) 
        {
            if (x / divisor != x % 10) 
            {
                return false;
            }
            x = (x % divisor) / 10;
            divisor /= 100;
        }
        return true;
    }
};




posted on 2014-09-25 13:12  gcczhongduan  阅读(138)  评论(0编辑  收藏  举报