码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-01-05 21:35:58      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:class   for   bsp   span   一半   bre   图片   判断   mil   

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 };

 

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

标签:class   for   bsp   span   一半   bre   图片   判断   mil   

原文地址:https://www.cnblogs.com/yocichen/p/10225997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!