Solution using 32-bit integer without overflow


  • 18
    T

    The idea is to reverse only half of the digits and compare them.

        public boolean isPalindrome1(int x) {
        if (x == 0) return true;
        // in leetcode, negative numbers and numbers with ending zeros
        // are not palindrome
        if (x < 0 || x % 10 == 0)
            return false;
    
        // reverse half of the number
        // the exit condition is y >= x
        // so that overflow is avoided.
        int y = 0;
        while (y < x) {
            y = y * 10 + (x % 10);
            if (x == y)  // to check numbers with odd digits
                return true;
            x /= 10;
        }
        return x == y; // to check numbers with even digits
    }

  • 6
    K

    You don't need to check x == y in the loop.

    // 393 ms
    class Solution {
    public:
        bool isPalindrome(int x) {
            if (x < 0 || x != 0 && x % 10 == 0)
                return false;
            int y;
            for (y = 0; y < x; x /= 10)
                y = y * 10 + x % 10;
            return (x == y || y / 10 == x ? true : false);
        }
    };

Log in to reply
 

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