判断一个整数是不是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是同样的整数。spa
示例 1:code
输入: 121 输出: true
示例 2:blog
输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。所以它不是一个回文数。
示例 3:io
输入: 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,则出了问题class
回文序列只须要判断一半就能够了。bug
官方答案di
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 }