搜索此博客

2013年1月23日星期三

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.

01 public boolean isPalindrome(int x) {
02     if(x<0)
03         return false;
04     if(x<10)
05         return true;
06       
07     int num=x;
08     int len=1;
09   
10     //calculate the length of x
11     while(num>=10)
12     {
13         num=num/10;
14         len=len*10;
15     }
16   
17     int leftDigit=0, rightDigit=0;
18     num=x;
19   
20     while(len>1)
21     {
22         leftDigit=num/len;
23         rightDigit=num%10;
24         if(leftDigit!=rightDigit)
25             return false;
26         num=(num%len)/10;
27         len=len/100;
28     }
29     return true;
30 }

没有评论:

发表评论