Naive Verbose O(2n)Java solution


  • 0
    D

    Any advice is welcome!

    public boolean isPalindrome(int x) {
            if(x<0) return false;
            long xx= (long)x;//initially added to consider -ve nums as palindromes also
            int n = countDigits(xx);
            if(n==1 || n==0 ) return true;
            
            int toMSD = n>>1;
            int toUnits = toMSD-1;
            if((n&1)==1){
                toMSD+=1;
            }
            
            while(toMSD<n && (getDigit(xx,toMSD))== (getDigit(xx,toUnits))){
                toUnits--;
                toMSD++;
            }
            return toMSD==(n);
        }
        
        public int countDigits(long x ){
            int count = 0;
            while(x!=0){
                x/=10;
                count++;
            }
            return count;
        }
        
        //pos starts from 0. 
        public int getDigit(long x,int pos){
            return (int)(x%(int)Math.pow(10,pos+1))/(int)Math.pow(10,pos);
        }
    

Log in to reply
 

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