首页 > 代码库 > [LeetCode] [Palindrome Number 2012-01-04]

[LeetCode] [Palindrome Number 2012-01-04]

Determine whether an integer is a palindrome. Do this without extra space.

if use recursive, like check the first dig and last dig, then remove them, check the rest, it will fail when digint like "1021", when remove the first and last one, the remaining would simply be "2", not "02". 

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
    bool isPalindrome(int x) {
        //Palindrome means 回文
         
        if(x < 0) return false;
        if(x <= 9) return true;
        int t = x;
        int n=0;
        while(t > 0)
        {
            n++;
            int d = t%10;
            t=(t-d)/10;
        }
         
         
        int* s = new int[n];
        t = x;
        n=0;
        while(t > 0)
        {
            int d = t%10;
            s[n++] = d;
            t=(t-d)/10;
        }
         
        for(int i = 0; i<n/2;i++)
        {
            if(s[i] != s[n-i-1])
            {
                return false;
            }
        }
        return true;
    }
};