【LeetCode】202. Happy Number
2016-04-27 16:23
417 查看
题目:
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
理解:
判断一个数是否”happy“。
“happy"的定义是:计算这个数各个位置上的数的平方和,再计算这个平方和各个位置上的数的平方和,循环得到平方和为1,则这个数”happy“;否则,若中间某个平方和的值之前已经出现过,则说明循环永远得不到平方和为1,则这个数不是happy number。
分析:
1.计算给定数(或当前平方和)各个位置上的数的平方和,若该平方和为1,返回true;否则转2;
2.判断这个平方和是否已经出现过,若已经出现过,返回false;否则转1。
由于要记录下已经出现的平方和的值,并且在下次要迅速检索到当前平方和是否已经出现过,因此如果用C++,使用map存储再合适不过了。
代码:
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
理解:
判断一个数是否”happy“。
“happy"的定义是:计算这个数各个位置上的数的平方和,再计算这个平方和各个位置上的数的平方和,循环得到平方和为1,则这个数”happy“;否则,若中间某个平方和的值之前已经出现过,则说明循环永远得不到平方和为1,则这个数不是happy number。
分析:
1.计算给定数(或当前平方和)各个位置上的数的平方和,若该平方和为1,返回true;否则转2;
2.判断这个平方和是否已经出现过,若已经出现过,返回false;否则转1。
由于要记录下已经出现的平方和的值,并且在下次要迅速检索到当前平方和是否已经出现过,因此如果用C++,使用map存储再合适不过了。
代码:
class Solution { public: bool isHappy(int n) { unordered_map<int, bool> m; int sum=GetSum(n); while(sum!=1) { if(m[sum]==true) return false; m[sum]=true; sum=GetSum(sum); } return true; } int GetSum(int num) { int sum=0; while(num!=0) { int digit=num%10; sum+=(digit*digit); num/=10; } return sum; } };
相关文章推荐
- 解决Gradle DSL method not found: ‘android()’
- Android开源项目SlidingMenu深入剖析
- Hibernate 二级缓存 Snappy 报错,提示 maxCompressedLength(I)I
- Service
- 使用ApplicationLoader中出现报错:The IPA is invalid. It does not inlude a Payload directory
- AndroidStudio常用快捷键
- iOS target specifies product type 'com.apple.product-type.bundle.ui-testing'
- 切换android SDK版本时出现的编译报错
- ios事件慢慢整理
- iOS 微信分享整理 - 自定义分享菜单
- objective-c 基础框架 属性列表等
- iOS 音频播放、录音、视频播放、拍照、视频录制
- 【Android问题记录】Android在设置中切换语言后,回到Lanucher为什么会白屏
- Android 仿qq消息 可拖动回弹的泡泡
- Fragment
- Android笔记--Activity
- Android版本更新
- iOS内存优化常用方法(更新中)
- 【iOS开发】如何查看真机的沙盒(图文教程)
- 将各种控件设置成圆形