straightforward solution with constant memory usage


  • 0
    F

    The code is

    bool isPalindrome(int x) {
            
            if (x < 0){
                return false;
            }
    
            int N = -1;
            int temp = x;
    
            do {
                ++N;
                temp = temp / 10;
    
            }while(temp);
    
            do {
                int low = x % 10;
                int high = x / pow(10, N);
    
                x -= high*pow(10,N);
                x /= 10;
                N -= 2;
    
                if (low != high){
                    return false;
                }
    
            } while (N >= 0);
    
            return true;
        }
    

    The idea is simple: we just get the first digit and last digit from the number, compare them and then remove first and last digit. Repeat the above steps until it returns or stops.


Log in to reply
 

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