Using long type AC


  • 0
    R

    Two way for palindrome problem: compare each left and right side element, or reverse and compare. Since Strings are not considered as constant space, we use second method. The only problem we have to deal is overflow, so I used a long type to restore result. X is a valid integer, so if we find reversed int is over range of integer, we should return false

    public boolean isPalindrome(int x) {
            if(x < 0)   return false;
            // if(x != 0 && x % 10 == 0) return false;
            long res = 0;
            int y = x;
            while(y != 0) {
                res = res * 10 + y % 10;
                y = y / 10;
                if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)  return false;
            }
            return res == x || res / 10 == x;
        }
    

Log in to reply
 

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