LeetCode【9】. Palindrome Number --java的实现
Palindrome Number
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.
推断一个int是否为回文。
一、思路1:
首先获取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; } }
二、思路2
复制将给定int从低位往高位開始。复制为另外一个高位至低位,得到一个给定值的反序。再比較两者是否相等。意思就是拿个镜子,然后照出镜子里跟自己左右相反的自己。假设是自己是全然对称的(这里是回文)。那例外两个看一起一定一模一样的。
Java代码例如以下:
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. 将两数进行比較并返回结果 } }