LeetCode 202. Happy Number
2016-04-17 06:53
375 查看
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
O(n) memory complexity solution has nothing special. Just read the problem carefully.....
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
O(n) memory complexity solution has nothing special. Just read the problem carefully.....
class Solution { private: set<int> integers; public: static int sumOfDigit(int n) { int sum = 0; while(n) { int tmp = n % 10; sum += tmp * tmp; n = n / 10; } return sum; } bool isHappy(int n) { int sum = sumOfDigit(n); if(sum == 1) return true; else { if(integers.find(sum) != integers.end()) return false; integers.insert(sum); return isHappy(sum); } } };
相关文章推荐
- Android学习(25) -- 单元测试(JUnit Test)
- Android应用的界面编程:ProgressBar及其子类[SeekBar、RatingBar]
- Android学习笔记(39):异步任务AsyncTask
- Android学习笔记(38):Handler消息传递处理机制
- Unity 使用 Stripping Level == Use micro mscorlib 导致 MD5.Create() 返回NULL
- Android Studio gradle总结
- AsyncTask的缺陷和问题
- Android学习笔记(37):用Configuration类获取和监听设备信息
- Android Animation (动画设计)
- Android学习--broadcast intent
- Android中使用Intent实现界面跳转
- 用u盘恢复路由器的ios
- Swift 类型转换is, as, Any, AnyObject(十二)
- android 6.0运行时权限的申请(微信在android 6.0上实现运行时请求权限的实现)
- android:Widget.Material.Button.Colored找不到
- Android-->圆角图片,圆角任意View,圆角父布局Layout(任意形状的View且超简洁实现)
- Android固件加载出错(load failed with error -2)
- IOS 退出程序代码
- Android学习笔记(36):Android的两种事件处理方式
- 内容观察者