Readable, Accepted Java Solution - Runtime of 197 ms (beats 90% of submissions)


  • 0
    U
    public class Solution {
        public boolean isPalindrome(int x) {
            return x == reverse(x); // x is a palindrome number if it's equal to it's reverse form.
        }
        
        private int reverse(int x) {
            
            if (x < 0) {
                return 0; // The system doesn't consider negative numbers to be palindromes.
            }
            int reversed = 0;
            
            while (x != 0) {
                int n = reversed * 10 + (x % 10);
                
                if (n / 10 != reversed) { // overflow?
                    return 0;
                }
                x = x / 10;
                reversed = n;
            }
            return reversed;
        }
    }
    

Log in to reply
 

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