9. 回文数

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

示例 1:

输入: 121
输出: true

示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

我的答案:
 1 class Solution {
 2     public boolean isPalindrome(int x) {
 3         if (x < 0)
 4             return false;
 5         
 6         int res = 0;
 7         int n = x;
 8         while (n != 0) {
 9             res = n % 10 + res * 10;
10             n = n / 10;
11         }
12         
13         if(res == x) 
14             return true;
15         else
16             return false;
17         
18     }
19 }

答案存在bug:如果数字太大,反转超过Interge.MAX,则出了问题

回文序列只需要判断一半就可以了。

官方答案

 1 public class Solution {
 2     public bool IsPalindrome(int x) {
 3         if(x < 0 || (x % 10 == 0 && x != 0)) {
 4             return false;
 5         }
 6 
 7         int revertedNumber = 0;
 8         while(x > revertedNumber) {
 9             revertedNumber = revertedNumber * 10 + x % 10;
10             x /= 10;
11         }
12 
13         return x == revertedNumber || x == revertedNumber/10;
14     }
15 }
原文地址:https://www.cnblogs.com/hello-lijj/p/9537494.html