Skip to content

Commit 28288ba

Browse files
author
programmerhjh
committed
日常水题
1 parent 168b248 commit 28288ba

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

src/myleetcode/PalindromeNumber.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package myleetcode;
2+
3+
/**
4+
* 回文数
5+
* @author acer
6+
*
7+
*/
8+
public class PalindromeNumber {
9+
10+
public static void main(String[] args) {
11+
System.out.println(isPalindrome(-121));
12+
}
13+
14+
public static boolean isPalindrome(int x) {
15+
boolean result = true;
16+
if (x < 0) {
17+
result = false;
18+
return result;
19+
}
20+
int times = 1;
21+
int x1 = x;
22+
while(x1 / 10 != 0) {
23+
x1 = x1 / 10;
24+
times ++;
25+
}
26+
if (times <= 1) {
27+
return result;
28+
} else if (times == 2 && x % 11 == 0) {
29+
return result;
30+
}
31+
boolean flag = true;
32+
int i = 1;
33+
int mid = times / 2;
34+
if (times % 2 == 0) {
35+
while (flag) {
36+
int left = (x / (int)Math.pow(10, mid+i-1)) % 10;
37+
int powRight = (int)Math.pow(10, mid-i+1);
38+
int right = x % powRight;
39+
if (right >= powRight/10) {
40+
right = right / (powRight / 10);
41+
} else {
42+
right = 0;
43+
}
44+
if (left != right) {
45+
result = false;
46+
break;
47+
}
48+
if (i + mid == times - 1) {
49+
flag = false;
50+
}
51+
i ++;
52+
}
53+
} else {
54+
while (flag) {
55+
int left = (x / (int)Math.pow(10, mid+i)) % 10;
56+
int powRight = (int)Math.pow(10, mid-i+1);
57+
int right = x % powRight;
58+
if (right >= powRight / 10) {
59+
right = right / (powRight / 10);
60+
} else {
61+
right = 0;
62+
}
63+
if (left != right) {
64+
result = false;
65+
break;
66+
}
67+
if (i + mid == times - 1) {
68+
flag = false;
69+
}
70+
i ++;
71+
}
72+
}
73+
return result;
74+
}
75+
76+
}

0 commit comments

Comments
 (0)