leetcode:Palindrome Number

时间:2023-03-09 08:04:03
leetcode:Palindrome Number

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):

 class Solution {
public boolean isPalindrome(int x) {
if(x<0)
return false;//如果是负数,返回不是回文数
if(0==x)
return true;
int length=0; //记录回文数位数
int xx=x;//xx作为x的备份
while(x>0){
x/=10;
length++;
}//求整数的位数
// System.out.println(length);
if(1==length)
return true;//一位数返回是回文数
int i=0;
int sum=0;
while(i<length/2){
sum=(sum+xx%10)*10;
xx/=10;
i++;
}//注意这里得到的sum多乘以了个10
// System.out.println(xx);
// System.out.println(sum);
if((length&0x1)==0&&xx==sum/10){ //如果数的长度是偶数,并且xx==sum/10那么返回是回文数
return true;
}
if((length&0x1)==1&&xx/10==sum/10){//如果数的长度是奇数,并且xx/10==sum/10那么返回是回文数
return true;
}
return false;//其他情况不是回文数
}
}