【LeetCode】202. Happy Number
2015-08-20 21:33
495 查看
题目:
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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
提示:
题目的关键其实是判断出计算happy number时是否陷入循环。一种是把每一步算出的平方和插入Hash Set中,如果已经存在这个数了,说明已经进入了循环状态,则该数不是happy number。另一种方法就是把平方和保存到数组(vector)中。然后每次遍历地去寻找该平方和是否曾经出现过。
虽然用Hash Set是O(1),对vector遍历是O(n),但是因为数字不多,因此用遍历的方法速度也很快。
纯数学方法:
关于happy number的循环序列有数学证明,我们可以通过判断平方和是否出现“4”来判断是否有循环。具体证明可以参看这篇文章。
代码:
下面给出利用vector遍历的方法:class Solution { public: bool isHappy(int n) { vector<int> nums; int result; while (true) { if (n == 1) return true; nums.push_back(n); result = 0; while (n != 0) { result += (n % 10) * (n % 10); n = n / 10; } for (int i = 0; i < nums.size(); ++i) { if (nums[i] == result) return false; } n = result; } } };
相关文章推荐
- Android--Activity的启动模式
- iOS 代码 AutoLayout
- android:TextAppearance.Material.Widget.Button.Inverse找不到或者报错问题
- ios线程-常用方法
- Android-本地启动服务的方法及调用方法的顺序
- Cocos2d-JS win32 获取远程图片失败
- 个人--跳槽--iOS职位要求
- 【读书笔记】iOS-Tagged Pointer对象-注意事项
- 【读书笔记】iOS-Tagged Pointer对象-注意事项
- [iOS]上下文的理解
- Android-自定义发送/接收广播(BroadcastReceiver)
- iOS8使用CoreLocation获取当前地理位置
- android 添加视频、图片、录音上传(三)
- android 添加视频、图片、录音上传(二)
- Cocos2d-x 之 八方向小摇杆
- android 添加视频、图片、录音上传(一)
- cocos2dx——cocostudio界面的使用详解
- swift 百度地图开发问题
- Android中的缩略图加载-不浪费一点多余的内存
- Swift ! 和 ? 区别