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.
因為之前做過數字倒序輸入的題目,所以我的想法就是算出他的倒序數字,然后進行對比。當然,從提示中我們可以看到,一些負數什么的,是不滿足條件的。所以,我們將負數刨除在外。
簡單的代碼就不寫了,結果就是寫了之后,貼上去,結果編譯不通過,郁悶。。應該還有其他的好的算法,哎,被虐的不要不要的。
看大家的討論內容,思路有了一些拓展,看到了評論最多的一個方法,貼出來如下:
public static boolean isPalindrome(int x) throws Exception { 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); }這個算法依舊很妙,沿用了之前數字倒序輸出的思路,但是有了一些變化。中間這一段算法的目的就是求出這個數字的后幾位數的倒序表示的數字。
比如,我們輸入的數字是1221,我們經過中間的循環,算出的rev=12,x=12,也就是算出了后面兩個數字21的倒序數,就是12,與前面的12相等,符合x==rev的條件,輸出true。還有一種情況就是數字的位數為奇數位,此時求出的rev是(位數/2+1)取整的倒序數字,比如數組12321,此時rev=123,x=12,滿足條件x==rev/10的條件,同樣的也能得到true。
看了討論,真是讓我汗顏啊~~~
新聞熱點
疑難解答