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;
实在是太精妙了。
相关文章推荐
- IOS--UI--LessonKOV
- why-they-are-using-vi
- (八十四)集成百度地图和基本使用
- hdu 4691 最长的共同前缀 后缀数组 +lcp+rmq
- CSS学习笔记——简述
- Expression parameters.parseContent is undefined on line 45
- HDOJ 2563 统计问题(递推)
- 单向链表
- NSTimer知识点和倒计时的实现
- JavaBean的一个小例子
- 股票学习(K线分析)
- Linux环境下列出指定目录下的所有文件
- SVM原理
- Python下opencv使用笔记(十一)(详解hough变换检测直线与圆)
- 2029 Palindromes _easy version
- cocos2dx游戏开发学习基础篇(一)
- 调试集群的一些方法收集
- web项目.注册及登陆
- poj2255 (二叉树遍历)
- 编译修改过的felix失败记录