Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
- 注意到这道题将所有负数都当做非回文数字,另外, 如果能用一个字符串去模拟这个数字然后再判断这个字符串是否回文串可以解这道题,但是这样不符合题目不能使用额外的存储空间的要求。所以必须得另外想办法。
Solution1
- 其实可以用Leetcode7中的翻转一个数字的方法来解决这道题,基本思路是:将原始数字进行翻转,翻转后来判断是否与原始数相等。代码如下:
public class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
int temp = 0;
for(int num=x;num>0;num/=10) temp = 10*temp + num%10;
if(temp==x) return true;
return false;
}
}
Solution2
- 解法一解题思路非常直白和明了。但是这还仍未充分利用到回文的特点,其实可以对原数进行一半的翻转。代码如下:
public class Solution {
public boolean isPalindrome(int x) {
if(x<0||(x!=0&&x%10==0)) return false;//下面的方法无法避免个位为0的数,所以必须特殊考虑
int temp = 0;
for(;x>temp;x/=10) temp = 10*temp + x%10;
return (temp==x)||(temp/10==x);//第一个判断针对形如"1221",第二个判断针对形如"121"
}
}