LeetCode练习-回文测试(Palindrome Number)

描述:

确定整数是否是回文。并且没有额外的空间。

我的测试:

在整数翻转的基础上进行修改

 public boolean isPalindrome(int x) {
        int befx=x;
	int rev = 0;
	if(x<0||(x%10==0&&x!=0)){
		return false;
	}
	while (x != 0) {
		if (rev != 0 && Integer.MAX_VALUE / rev < 10
				&& Integer.MAX_VALUE / rev > -10)
			rev =  0;
		rev = rev * 10 + x % 10;
		x = x / 10;
	}
	if(befx==rev){
		return true;
	}
	return false;
    }

LeetCode给出的答案:

public boolean IsPalindrome(int x) {
        // Special cases:
        // As discussed above, when x < 0, x is not a palindrome.
        // Also if the last digit of the number is 0, in order to be a palindrome, 
        // the first digit of the number also needs to be 0.
        // Only 0 satisfy this property.
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        
        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        
        // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
        // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123, 
        // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
        return x == revertedNumber || x == revertedNumber/10;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值