Sharing my simple and straightforward solution with explanation

  • 13
    bool isPalindrome(int x) {
        long reverse = 0;
        long num = abs(x);
        while(x != 0){
            reverse *= 10;
            reverse += x % 10;
            x /= 10;
        return reverse == num;

    The basic idea is to reverse x.

    However, we need to handle two issues. First of all, what if reverse number overflows? We use long to solve. Secondly, negative number doesn't have palindrome. So we make num = abs(x).

Log in to reply

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