File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
src/main/java/com/chen/algorithm/study Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .chen .algorithm .study .test7 ;
2+
3+ /**
4+ * @Auther: zhunn
5+ * @Date: 2020/9/16 18:20
6+ * @Description:
7+ */
8+ public class Solution4 {
9+
10+ public static int reverse1 (int x ) {
11+ int res = 0 ;
12+ while (x != 0 ) {
13+ res = res * 10 + x % 10 ;
14+ x /= 10 ;
15+ }
16+ if (res < Integer .MIN_VALUE || res > Integer .MAX_VALUE ) {
17+ return 0 ;
18+ }
19+ return res ;
20+ }
21+
22+ public static void main (String [] args ) {
23+ System .out .println (reverse1 (123 ));
24+ }
25+ }
Original file line number Diff line number Diff line change 1+ package com .chen .algorithm .study .test9 ;
2+
3+ /**
4+ * @Auther: zhunn
5+ * @Date: 2020/9/16 18:22
6+ * @Description:
7+ */
8+ public class Solution4 {
9+
10+ public static boolean isPalindrome1 (int x ) {
11+ // 特殊情况:
12+ // 当 x < 0 时,x 不是回文数。
13+ // 同样地,如果数字的最后一位是 0,为了使该数字为回文,
14+ // 则其第一位数字也应该是 0
15+ // 只有 0 满足这一属性
16+ if (x < 0 || (x != 0 && x % 10 == 0 )) return false ;
17+ int rev = 0 ;
18+ while (x > rev ) {
19+ rev = rev * 10 + x % 10 ;
20+ x /= 10 ;
21+ }
22+ // 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
23+ return rev == x || rev / 10 == x ;
24+ }
25+
26+ public static void main (String [] args ) {
27+ System .out .println (isPalindrome1 (-121 ));
28+ System .out .println (isPalindrome1 (0 ));
29+ System .out .println (isPalindrome1 (1000 ));
30+ System .out .println (isPalindrome1 (12321 ));
31+ System .out .println (isPalindrome1 (1221 ));
32+ System .out .println (isPalindrome1 (1231 ));
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments