Palindrome Number

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.

思路一:

提取各个位进行比较即可,注意在最初确定最高位的数量级时while中的条件是x/highDivisor >= 10。

 1 public boolean isPalindrome(int x) {
 2         if(x<0) {
 3             return false;
 4         }
 5         int highDivisor = 1;
 6         while(x/highDivisor >= 10) {
 7             //注意条件
 8             highDivisor *= 10;
 9         }
10         while(x != 0) {
11             int low = x%10;
12             int high = x/highDivisor;
13             if(low != high) {
14                 return false;
15             }
16             //去掉最高位和个位
17             x = (x % highDivisor)/10;
18             highDivisor /= 100;
19         }
20         return true;
21     }

P.S.虽然这是道Easy的题,在Accept的过程中还是纠结了一会,最后一直报Time Limit Exceeded,后来发现是把一个调试时的System.out.println()命令带进去了,去掉之后就OK了,这种细节还是要注意一下!

posted on 2015-03-20 10:36  绿树荫  阅读(123)  评论(0编辑  收藏  举报

导航