Leetcode 9 Palindrome Number

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"
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值