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.
判断一个int是否为回文。
首先获取int长度,再从两头往中间扫描,将对称的元素成对进行比较。代码如下,但是Time Limit Exceeded超时了。
public class Solution { public boolean isPalindrome(int x) { int xl; if(x<0) //1.小于0 return false; for(xl = 1;x/(xl*10)>0;xl++) //2. 得到x的长度 ; if(xl==1) //3.x为个位数时直接返回(因为后续处理个位数时会使分母为0,故单独处理) return true; for(int i=2;(xl/2)>=i;i++) { if(x%(i*10)/((i-1)*10) == x%((xl-i+1)*10)/((xl-i)*10)) //4.分别取对称的两个数进行比较 { }else return false; } return true; } }
public class Solution { public boolean isPalindrome(int x) { int t=x; int re=0; if(x<0) //1. 负数无法为回文 return false; while(t>0) //2. 判断是否将t的所有位数取完 { re = re*10+t%10; //3. 将t的最后一位拼接在re的后面 t = t/10; } return x==re; //4. 将两数进行比较并返回结果 } }
LeetCode【9】. Palindrome Number --java的实现
原文:http://blog.csdn.net/waycaiqi/article/details/46399659