## Friday, December 28, 2012

### [LeetCode] 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.
» Solve this problem

[解题思路]

[Code]
``````1:    bool isPalindrome(int x) {
2:      // Start typing your C/C++ solution below
3:      // DO NOT write int main() function
4:      if(x<0) return false;
5:      int orig = x;
6:      int s=1, e=10;
7:      while(x/10>0)
8:      {
9:        s*=10;
10:        x/=10;
11:      }
12:      int xl = orig, xr = orig;
13:      while(s>=e)
14:      {
15:        int lv = xl/s;
16:        xl= xl- xl/s *s;
17:        int rv = (xr- xr/e *e)/(e/10);
18:        xr = xr/e*e;
19:        if(lv!=rv)
20:          return false;
21:        s=s/10;
22:        e=e*10;
23:      }
24:      return true;
25:    }
``````

[已犯错误]
1. Line 17.

Update: 3/5/2013
Refactor the code to make it simple.
``````1:       bool isPalindrome(int x) {
2:            if(x<0) return false;
3:            int div = 1;
4:            while(x/div >=10)
5:                div*=10;
6:            while(x>0)
7:            {
8:                 int l = x/div;
9:                 int r = x%10;
10:                 if(l!=r) return false;
11:                 x=x%div/10;
12:                 div/=100;
13:            }
14:            return true;
15:       }
``````