009.Palindrome Number

Solution 1: accepted

The given number has to be an integer. So “if (reversed > 214748364 || reversed < -214748364)” would be fine.
Even if it is a fit, the is not a palindrome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || x >= 2147483642) // making huge difference in performance, probably due to the speciality of the test cases
return false;
int original = x;
int reversed = 0;
int digit = 0;
while (x != 0) {
if (digit == 9) {
if (reversed > 214748364 || reversed < -214748364)
return false;
}
reversed = reversed * 10 + x % 10;
x = x / 10;
digit++;
}
return original == reversed;
}
}

Solution 2: accepted 261ms

Simplified. But do we need to check the entire number?

1
2
3
4
5
6
7
8
9
10
11
public boolean isPalindrome(int x) {
if (x < 0 || x > 0 && x % 10 == 0)
return false;
int original = x;
int reverse = 0;
while (x != 0) {
reverse = reverse * 10 + x % 10;
x /= 10;
}
return reverse == original;
}
Improvement: accepted 221ms

We only need to check half of the number

1
2
3
4
5
6
7
8
9
10
public boolean isPalindrome(int x) {
if (x < 0 || x > 0 && x % 10 == 0)
return false;
int reverse = 0;
while (x > reverse) {
reverse = reverse * 10 + x % 10;
x /= 10;
}
return (x == reverse || x == reverse/10); // for 123321 and 12321
}