In-place solution using just arithmetic.


  • 0
    P
    unsigned powint(unsigned base, unsigned exp)
    {
        unsigned pow = base;
        for(unsigned i = 0; i < exp; i++ )
        {
            pow *= base;
        }
        return pow;
    }
    
    class Solution {
    public:
        bool isPalindrome(int x) {
            
            if(INT_MIN == x) return false;
            
            if(x < 0)
            {
                return false;
            }
    
            int maxExp = 0;
            for(int temp = x; temp > 9; temp /= 10)
            {
                maxExp++;
            }
    
            int largestPower = 0;
            int leftDigit = 0;
            int rightDigit = 0;
            for( ; maxExp > 0; maxExp -= 2 )
            {
                largestPower = powint(10, maxExp - 1);
                leftDigit = (x - x % largestPower) / largestPower;
                rightDigit = x % 10;
    
                if(leftDigit != rightDigit)
                {
                    return false;
                }
    
                x = (x - leftDigit * largestPower) / 10;
            }
    
            return true;
        }
    };

  • 0
    J

    cool. Thanks.

    I have the similar code but I can't handle 100051.

    But, actually, there are some extra space occupation.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.