leetcode 9

判断一个数是否为回文数,不利用额外的空间。

思路:将数反转后进行比较。

注意:反转之后数越界的判断,若越界,则不是回文数;负数不是回文数;

代码如下:

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         int result = 0;
 5         int y = x;
 6         if(x == 2147483648 || x < 0)
 7         {
 8             return false;
 9         }
10         if(abs(x) < 1000000000)
11         {
12            while(x != 0)
13            {
14               result = result * 10 + x % 10;
15               x = x / 10;
16            }
17        }
18        else
19        {
20            int a[10] = {2,1,4,7,4,8,3,6,4,8};
21            int i = 0;
22            int flag = abs(x);
23            while(flag != 0)
24            {
25                if((flag % 10) > a[i])
26                {
27                     return 0;
28                }  
29                else if((flag % 10) < a[i])
30                {
31                    while(x != 0)
32                    {
33                        result = result * 10 + x % 10;
34                        x = x / 10;
35                    }
36                    if(result == y)
37                    {
38                         return true;
39                    }
40               }
41               flag /= 10;
42               i++;
43             }
44         }
45         if(result == y)
46         {
47             return true;
48         }
49         return false;
50     }
51 };

 

posted @ 2016-09-01 21:06  花椰菜菜菜菜  阅读(175)  评论(0编辑  收藏  举报