leetcode-9.回文数(水仙花数)

leetcode-9.回文数(水仙花数)

题意:给定整数,判断是否是水仙花数(回文数),返回判断结果

算法:

1.判断负数, 如果是负数直接返回false
2.将整数逐位拆解,用数组存储
3.遍历数组,若本位与后面对应位不等返回false.

Code

 1 class Solution {
 2 public:
 3     bool isPalindrome(int x) {
 4         if(x < 0)
 5             return false;//负数,直接返回false
 6         int perBit[32+2];//数组,用于存储数字每一位
 7         int count=0;
 8         bool flag = true;
 9         while(x)//数字数组化
10         {
11             perBit[count] = x%10;
12             x /= 10;
13             count++;
14         }
15         for(int i=0; i<count; i++)//遍历数组(其实是遍历一般)
16         {
17             if(perBit[i] != perBit[count-1-i])//对应位置值不等,不是,返回false
18             {
19                 return false;
20             }
21             if(i == count/2)//扫一半就够了
22                 break;
23         }
24         return flag;//若是,返回true
25     }
26 };

猜你喜欢

转载自www.cnblogs.com/yocichen/p/10225997.html