forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeInteger.java
More file actions
51 lines (49 loc) · 1.37 KB
/
PalindromeInteger.java
File metadata and controls
51 lines (49 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//Compare number by number, never overflow, in constant space
public class Solution {
public boolean isPalindrome(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x < 0) return false;
int div = 1;
//find largest divisor
while(x/div >= 10)
div *= 10;
while(div > 1){
int l = x / div;
int r = x % 10;
if(l != r) return false;
x = (x % div)/10;
div /= 100;
}
return true;
}
}
//Reverse first, then compare, might overflow
public class Solution{
public boolean isPalindrome(int x){
if(x < 0)
return false;
int y = reverseInt(x, 0);
if(x == y)
return true;
return false;
}
public int reverseInt(int x, int remain){
if(x / 10 == 0)
return remain * 10 + x;
else{
remain = remain * 10 + x %10;
return reverseInt(x / 10, remain);
}
}
}
//Easy, short, use Extra Space
public class Solution{
public boolean isPalindrome(int x) {
String xs = String.valueOf(x);
for(int i = 0, j = xs.length() - 1; i < j; ++i, --j)
if(xs.charAt(i) != xs.charAt(j))
return false;
return true;
}
}