9. Palindrome Number
2016-07-15 11:47
218 查看
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?
There is a more generic way of solving this problem.
使用额外空间
public static boolean isPalindrome(int x)
{
if(x<0)
return false;
char[] carr=new char[10];
int cnt=0;
while(x>0)
{
carr[cnt++]=(char) (x%10+'0');
x=x/10;
}
boolean pa=true;
if(cnt%2==0)
{
for(int i=cnt/2-1,j=cnt/2;i>=0&&j<cnt;i--,j++)
if(carr[i]!=carr[j])
{
pa=false;
break;
}
}
else {
int mid=cnt/2;
for(int i=mid-1,j=mid+1;i>=0&&j<cnt;i--,j++)
if(carr[i]!=carr[j])
{
pa=false;
break;
}
}
return pa;
}
非常好的,不用额外空间,不用检查溢出的方法,摘自 https://discuss.leetcode.com/topic/8090/9-line-accepted-java-code-without-the-need-of-handling-overflow/2
public boolean isPalindrome(int x) {
if (x<0 || (x!=0 && x%10==0)) return false;
int rev = 0;
while (x>rev){
rev = rev*10 + x%10;
x = x/10;
}
return (x==rev || x==rev/10);
}
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?
There is a more generic way of solving this problem.
使用额外空间
public static boolean isPalindrome(int x)
{
if(x<0)
return false;
char[] carr=new char[10];
int cnt=0;
while(x>0)
{
carr[cnt++]=(char) (x%10+'0');
x=x/10;
}
boolean pa=true;
if(cnt%2==0)
{
for(int i=cnt/2-1,j=cnt/2;i>=0&&j<cnt;i--,j++)
if(carr[i]!=carr[j])
{
pa=false;
break;
}
}
else {
int mid=cnt/2;
for(int i=mid-1,j=mid+1;i>=0&&j<cnt;i--,j++)
if(carr[i]!=carr[j])
{
pa=false;
break;
}
}
return pa;
}
非常好的,不用额外空间,不用检查溢出的方法,摘自 https://discuss.leetcode.com/topic/8090/9-line-accepted-java-code-without-the-need-of-handling-overflow/2
public boolean isPalindrome(int x) {
if (x<0 || (x!=0 && x%10==0)) return false;
int rev = 0;
while (x>rev){
rev = rev*10 + x%10;
x = x/10;
}
return (x==rev || x==rev/10);
}
相关文章推荐
- Genymotion解决经常打开快速搜索框
- Jetson TK1 血泪开发记(一)——Jetson TK1初体验
- Gson json,list,model互转
- 机房合作——我们开工了!!!
- Codeforces 696D. Legen...
- Spark Shuffle 详解(1)
- 简单总结shiro标签
- 某天想做某事于是...
- Kerberos and SPNEGO
- Android Studio 出现call requires api level 11 (current min is 2)解决方法
- Android Draw PorterDuffXfermode
- Java程序员必须掌握的8大排序算法
- linux安装nginx
- 轻松实现可扩展自定义的Android滚轮时间选择控件
- Android Studio自定义模板代码
- web前端知识汇总-浏览器兼容(主要IE)
- spark配置选项
- windows系统下Python环境的搭建
- shiro的基本认识
- WEB开发--上线(转)