[LeetCode] No. 9 Palindrome Number

[题目] Determine whether an integer is a palindrome. Do this without extra space.

[题目解析] 判断一个给定整数是否为回文数,回文数即121,11411这种正着和反着相同的数字,最小的回文数是0。实现思路可以比较直接,先对int进行reverse,这个可以参考

http://www.cnblogs.com/zzchit/p/5806956.html,然后和给定数字比较即可。但是这道题困难的在这里“Do this without extra space.”,这就需要另想它法。然而并没有想到不需要额外空间的方法,

所以只能把题目规定的"额外空间"不包括这种O(1)的空间。如有好的方法,再做讨论。根据直接的思路,可以对reverse integer的代码进行化简,如下。

1   public boolean isPalindrome(int x) {
2         if(x < 0 || (x>0 && x%10==0)) return false;
3         int result = 0;
4         while(x > result){
5             result = result*10+x%10;
6             x/=10;
7         }
8         return (x == result || x == result/10);
9     }

 

posted @ 2016-08-26 12:09  三刀  阅读(110)  评论(0编辑  收藏  举报