Palindrome Number(回文数字)

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

题目很简单,判断一个int是否是回文数字,需要注意的几点:

1. 负数不为回文数字

2. 不能使用额外的空间,如果将该int转成string处理,会使用额外的空间

3.如果使用将该int反转,然后比较与原int是否相等这种判断方法,需要处理int溢出的问题,比如2147483647,反转过来就大于了Interger.MAXVALUE


我先采用第三种解法,代码如下:

public boolean isPalindrome(int x) {
        if(x < 0 )
        	return false;
        int org = x;
        int rev = 0;
        while( org > 0){
        	if(Integer.MAX_VALUE / 10 < rev)
        		return false;
        	rev = rev * 10 + org % 10;
        	org = org / 10;
        }
        return rev == x;
    }


如果反转之后产生了越界,说明int的最高位数字与个位数字不相等,可直接断定不为回文数字


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值