9. 回文数

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true
 1 public class PalindromeNumber {
 2     //方法一:直接获取倒序数
 3     public static boolean palindromeNumber(int x) {
 4         if(x < 0) {
 5             return false;
 6         }
 7         int result = 0;
 8         int temp = x;
 9         while(temp != 0) {
10             int lastNum = temp % 10;
11             temp /= 10;
12             result  = result * 10 + lastNum;
13         }
14         if(result == x) {
15             return true;
16         }
17         return false;
18     }
19     
20     //方法二:使用字符串数组两端遍历
21     public static boolean palindromeNumber3(int x) {
22         if(x < 0) {
23             return false;
24         }
25         String s = String.valueOf(x);
26         int left = 0;
27         int right = s.length()-1;
28         while(left < right) {
29             if(s.charAt(left) != s.charAt(right)) {
30                 return false;
31             }
32             left++;
33             right--;
34         }
35         return true;
36     }
37 }

 

posted @ 2019-05-22 21:27  往南的小燕子  阅读(136)  评论(0编辑  收藏  举报