Java with recursive pattern, I think it's too complex, could anyone point out the places to improve


  • 0
    S
    public class Solution {
        public boolean isPalindrome(int x) {
            int cnt = 0;
            int header = x;
            int tailer = 0;
            int tmp = 0;
            int cntTmp = 0;
            
            if(x < 10 && x >= 0){
                return true;
            } else if (x < 0) {
                return false;
            }
            
            while(header >= 10) {
                header = header / 10;
                cnt++;
            }
            tailer = x % 10;
            
            x = (x - tailer - header*(int)(Math.pow(10, cnt)))/10;
            tmp = x;
            while(tmp >= 10) {
                tmp = tmp / 10;
                cntTmp++;
            }
            if((cnt - cntTmp) > 2) {
                if((x%(int)(Math.pow(10, cnt-cntTmp-2))) != 0) {
                    return false;
                } else {
                    x = x / (int)(Math.pow(10, cnt-cntTmp-2));
                }
            }
            
            if(!isPalindrome(x)) {
                return false;
            }
            
            return header == tailer;
        }
    }

Log in to reply
 

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