Easy to understand with explanation..clean code


  • 0
    W

    The main idea is to test whether the reversion of the lower half of x is equal to the higher half of x, say, for x = 1234321, we test whether 123 == re(321) = 123, There is only one special case we need to take care of.. that is if x is something like ###0 which makes separating the x diffcult. but as you can see, if x is in this pattern, it is obviously not a Palindrome, so we could just return false.
    ·The idea comes from the forum.

    public class Solution {
        public boolean isPalindrome(int x) {
            if(x == 0)
                return true;
            if(x < 0 || x % 10 == 0)
                return false;
            int v = 0;
            while(x > v) {
                v = x % 10 + v * 10;
                x = x / 10;
            }
            return x == v || v / 10 == x;
        }
    }

Log in to reply
 

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