LeetCode: Palindrome Number

Question:

Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.


Thinking:

In my code, I compare the digits of an integer symmetrically. For example, integer 101, I compare the first digit with last digit; integer 1221, I compare the first with last, and 2nd with 3rd digits.

To do this, I first need to know the length of the integer, and then used a loop to do my comparisons.

Special case: remember that any negative number is not a palindrome number

public static boolean isPalindrome(int x) {
    long length = 1, pow = 10;
    if (x < 0) return false;

    while (x / pow != 0) {
    	length++;
    	pow *= 10;
    }

    long halfLength = length / 2;
    for (int i = 0; i < halfLength; i++) {
    	pow /= 10;
    	int back = x % 10;
    	long front = x / pow;
    	x = (int) (x % pow);
    	x /= 10;
    	pow /= 10;
    	if (front != back) return false;
    }

    return true;
}

 

Author: Jerry Wu

Keep moving forward!

Leave a comment