1
+ /*
2
+ Author: Andy, nkuwjg@gmail.com
3
+ Date: Aug 22, 2013
4
+ Problem: Palindrome Number
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/palindrome-number/
7
+ Notes:
8
+ Determine whether an integer is a palindrome. Do this without extra space.
9
+ Some hints:
10
+ Could negative integers be palindromes? (ie, -1) (No!)
11
+ If you are thinking of converting the integer to string, note the restriction of using extra space.
12
+ You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
13
+ you know that the reversed integer might overflow. How would you handle such case?
14
+ There is a more generic way of solving this problem.
15
+
16
+ Solution: 1. Count the number of digits first (traverse once) then check the digits from both sides to center.
17
+ 2. Reverse the number, then check to see if x == reverse(x).
18
+ 3. Recursion (interesting but a little hard to understand). -> See C++.
19
+ */
20
+ public class Solution {
21
+ public boolean isPalindrome (int x ) {
22
+ return isPalindrome_2 (x );
23
+ }
24
+ public boolean isPalindrome_1 (int x ) {
25
+ if (x <0 )return false ;
26
+ int d =1 ;
27
+ while (x /d >=10 )d *=10 ;
28
+ while (d >1 ) {
29
+ if (x %10 !=x /d )return false ;
30
+ x = (x %d ) /10 ;
31
+ d /=100 ;
32
+ }
33
+ return true ;
34
+ }
35
+ public boolean isPalindrome_2 (int x ) {
36
+ if (x <0 )return false ;
37
+ return x ==reverse (x );
38
+ }
39
+ public int reverse (int x ) {
40
+ int res =0 ;
41
+ while (x >0 ) {
42
+ res =res *10 +x %10 ;
43
+ x =x /10 ;
44
+ }
45
+ return res ;
46
+ }
47
+ }