leetcode:Palindrome Number

本文提供了一种判断整数是否为回文数的算法,时间复杂度为O(1),适用于负数和正数。详细解释了如何在不使用额外空间的情况下实现这一目标,包括处理负数和长度为1的特殊情况,以及通过计算整数的长度和反转后半部分来验证是否为回文数。

Question

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

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?

There is a more generic way of solving this problem.

判断一个数是不是回文数,时间复杂度要求为O(1)

注意的地方:负数是不是回文数?不是的话返回-1(其实负数不是回文数),如果你在想把整数转化为字符串,注意空间复杂度的限制,你当然可以想去把这个整数反序,但是你得考虑反序后的整数有可能发生溢出,你怎么去解决这个问题?有更多一般的方法可以去解决这个问题。

算法思路:① 对于负数进行判断,是的话返回不是回文数,0单独拿出,返回是回文数;

     ② 先求得数的长度length,如果length==1那么说明数一位,返回是回文数,如果length>1,则取这个整数后半部分的数,并反序;

     ③ 判断经过处理后反序的数和前一部分是否相等,length为奇数或者偶数要分开处理,相等的话返回回文数。

代码实现(java)

 

 1 class Solution {
 2     public boolean isPalindrome(int x) {
 3         if(x<0)
 4             return false;//如果是负数,返回不是回文数
 5         if(0==x)
 6             return true;
 7         int length=0; //记录回文数位数
 8         int xx=x;//xx作为x的备份
 9         while(x>0){
10             x/=10;
11             length++;
12         }//求整数的位数
13 //        System.out.println(length);
14         if(1==length)
15             return true;//一位数返回是回文数
16         int i=0;
17         int sum=0;
18         while(i<length/2){
19             sum=(sum+xx%10)*10;
20             xx/=10;
21             i++;
22         }//注意这里得到的sum多乘以了个10
23 //        System.out.println(xx);
24 //        System.out.println(sum);
25         if((length&0x1)==0&&xx==sum/10){  //如果数的长度是偶数,并且xx==sum/10那么返回是回文数
26             return true;
27         }
28         if((length&0x1)==1&&xx/10==sum/10){//如果数的长度是奇数,并且xx/10==sum/10那么返回是回文数
29             return true;
30         }
31         return false;//其他情况不是回文数
32     }
33 }

 

 

 

转载于:https://www.cnblogs.com/zhaolizhen/p/PalindromeNumber.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值