[LeetCode] 9. Palindrome Number

Problem

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

1
2
Input: 121
Output: true

Example 2:

1
2
3
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

1
2
3
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

Explanation

  1. If the number is 0, we return true; if the number is negative, we return false.

  2. We can reverse the number, and compare it with the current number. If they are the same, that means the number is palindrome; else the number is not a palindrome.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    int reverse (int x) {
        int res = 0;
        while (x != 0) {
            if (res > Integer.MAX_VALUE/10) return -1;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }

    public boolean isPalindrome(int x) {
        if (x == 0) return true;
        if (x < 0) return false;
        return reverse(x) == x;
    }
}