C++ Solution, using log10 which isn't very nice!


  • 0

    Pretty well commented, but uses log10 + floor to get the number of digits in the number; after looking at other solutions on this site, I have seen much 'nicer' ways of solving this problem, but I am sharing anyway!

    class Solution {
    public:
        bool isPalindrome(int x) {
            // A negative number is never going to be a palindrome.
            if ( x < 0 )
                return false;
                
            // How many digits are in this number.
            int numDigits = floor(log10(x)) + 1;
            
            // Go through half the digits (can integer round down as we don't care about the middle number if there is one).
            for ( int i = 0; i < numDigits / 2; ++i ) {
                // Get the right number with a simple modulus.
                int right = x % 10;
                
                // Get the multiplier to effect the left number.
                int d = pow( 10, numDigits - i*2 - 1 );
                
                // Divide by multiplier to get left most digit.
                int left = x / d;
                
                // If left/right do not match then return false.
                if ( left != right )
                    return false;
                    
                // Reduce number by left digit times multiplier.
                x -= d * left;
                
                // Remove right digit.
                x /= 10;
            }
            
            // Seems valid.
            return true;
        }
    };

Log in to reply
 

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