您的位置:首页 > 其它

LeetCode 9 Palindrome Number

2015-07-23 21:29 281 查看


Palindrome Number



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




有了回文字符串的基础这道题其实不难,在不借助字符串的基础上,转化为整型数组处理。


public boolean isPalindrome(int x) {
if(x<0)return false;
if(x<10&&x>-1)return true;
int []px = new int[10];
int i=0;
while(x>0){
px[i] = x%10;
x=x/10;
i++;
}
if(i%2==0){
int j = i/2;
int k = j-1;
while(k>=0){
if(px[j]!=px[k]){
return false;
}
k--;
j++;
}
}else{
int j=i/2-1;
int k=i/2+1;
while(k>=0){
if(px[j]!=px[k]){
return false;
}
k--;
j++;
}
}
return true;
}


Discuss上有个巧妙的算法:


class Solution {
public:

bool isPalindrome(int x) {
if(x<0)
return false;

int num=x;
int a=0;
while(x)
{
a=a*10 + x%10;
x=x/10;
}
if(a==num)
return true;
else
return false;

}
};




这个算法比我的更优,没有利用额外的数组空间。因为使用了px迭代之后,本身就是该数的回文序列。因此,只需要判断该数是否等于原数即可。我当时怎么没想到,这么容易。这也是之前几道题常用的迭代方法,对于数字字符串来说非常有用。关键部分代码为:


px = px*10+x%10;


x=x/10;


实在是太精妙了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: