LeetCode:Happy Number
2015-09-10 22:12
411 查看
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle
which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 =
1
Credits:
Special thanks to @mithmatt and @ts for
adding this problem and creating all test cases.
解题思路:建立一个vector,里面装得是新生成的数字,如例子中的19,82,68,100,每次产生一个新的数字就到这个vector中查询是否已经存在,如果已经存在,则必定会陷入循环;如果不存在,则加入到vector,继续生成新的数字。
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle
which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 =
1
Credits:
Special thanks to @mithmatt and @ts for
adding this problem and creating all test cases.
解题思路:建立一个vector,里面装得是新生成的数字,如例子中的19,82,68,100,每次产生一个新的数字就到这个vector中查询是否已经存在,如果已经存在,则必定会陷入循环;如果不存在,则加入到vector,继续生成新的数字。
class Solution { public: vector<int> vec; bool isHappy(int n) { if(n==1) return true; vector<int>::iterator it=find(vec.begin(),vec.end(),n); if(it==vec.end()){//在vector中没有找到该数字。 vec.push_back(n); int total=0; while(n){ total+=(n%10)*(n%10); n/=10; } return isHappy(total); }else{ return false; } } };
相关文章推荐
- 为什么选择CocoaPods进行iOS代码的管理
- (3)实体和结构【利用objective-c的runtime特性,结合FMDB实现轻量级的ORM】
- ios开发一些零碎的知识点(一)
- 色相(H)饱和度(S)明度(L)与RGB的转换以及在android上的试验
- 安卓判断是否首次进入app,通过判断跳转欢迎引导界面和主界面
- 安卓开发中Theme.AppCompat.Light报错的解决方法
- Android UTF-8转码
- Android中的SQLite数据库的简单使用
- MAC OS X10.10上Android开发环境搭建
- Android 属性动画
- Android的消息机制之ThreadLocal的工作原理
- Android里ListView里面添加CheckBox实现单选。
- Android学习笔记20150910
- Android 实现ListView的A-Z字母排序和过滤搜索功能,实现汉字转成拼音
- android多线程之AsyncTask
- iOS开发中 在MRC中让某些类使用ARC编译 或者相反
- iOS开发中 在MRC中让某些类使用ARC编译 或者相反
- APP产品设计流程图
- Android studio 目录结构
- Android应用资源系列之属性(Attribute)资源