Simple Java solution without extra space usage. (overflow considered)


  • 1
    D

    We reverse this integer but skip the highest digit to prevent overflow.

    For example, if we have 54345, then we reverse it and get 5434(Skip the highest digit), then we compare 54345 / 10 with 5434 and compare the last remaining digit x = 5(which we skipped) with the lowest digit of the original integer 54345 % 10. If they all match, then we can say it is a Palindrome Number.

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

Log in to reply
 

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