My 46ms C solution O(n) time, O(1) space


  • 0
    A
    int pow(int num, int pow){
        int result = 1 ;
        while(pow > 0 ){
            result = result * num;
            pow = pow - 1; 
        }
        return result;
    }
    
    bool isPalindrome(int x) {
        
        int num = x ; 
        int numDigits = 0; 
        
        if(x < 0 ){
            return false;
        }
    
        while(num > 0){
            num = num/10;
            numDigits++;
        }
        
        if(numDigits == 1 || numDigits == 0 ){
            return true;
        }
        
        
        int right = 1 ; 
        int left  = numDigits -1 ;
        num = x ; 
        while( right <= left ){
            
            int leftDigit  =  (  num / pow( 10, left  )  ) % 10 ;
            int rightDigit =  (num  % pow(10,right) ) / pow(10,right-1) ;
            
            if(leftDigit != rightDigit){
                return false;
            }
            
            left  = left  - 1; 
            right = right + 1;
    
        }
        
        return true;
        
    }

Log in to reply
 

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