Happy Number -- leetcode
2015-07-11 22:44
176 查看
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
算法一,
既然有死循环的可能,使用一个集合,记录已经访问过的数字。如果在集合中出现,则出现了循环。
在leetcode上用时8ms。
算法二,快慢指针
使用集合到底会额外占空间。
此处使用快慢指针的概念,来探知是否存在死循环。
在leetcode上实际执行时间为4ms。
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
算法一,
既然有死循环的可能,使用一个集合,记录已经访问过的数字。如果在集合中出现,则出现了循环。
在leetcode上用时8ms。
class Solution { public: bool isHappy(int n) { unordered_set<int> visited; while (n != 1 && !visited.count(n)) { visited.insert(n); int number = 0; while (n) { number += (n % 10) * (n % 10); n /= 10; } n = number; } return n == 1; } };
算法二,快慢指针
使用集合到底会额外占空间。
此处使用快慢指针的概念,来探知是否存在死循环。
在leetcode上实际执行时间为4ms。
class Solution { public: bool isHappy(int n) { int slow = n, fast = n; do { slow = next(slow); fast = next(next(fast)); } while (slow != fast); return slow == 1; } int next(int n) { int ans = 0; while (n) { ans += (n % 10) * (n % 10); n /= 10; } return ans; } };
相关文章推荐
- android 账户管理
- Android开发之BroadcastReceiver的使用
- Swift结构体和类
- iOS中的事件处理
- 设计复杂的 iOS 动画效果
- 利用内存结构及多线程优化多图片下载(IOS篇)
- android studio SSL BKS格式keystore文件加载
- Objective-C 中 nil/NULL/NSNull
- iOS阶段学习第17天笔记(NSFileManager-NSFileHandle-文件操作)
- 【Android Studio】代码混淆与多渠道打包
- android studio R文件丢失 解决方法
- [Android 性能优化系列]降低你的界面布局层次结构的一部分
- iOS:使用MVC模式帮ViewController瘦身
- 快速Android开发系列通信篇之EventBus
- IOS开发中的几种设计模式介绍
- [UI组件基础] 制作一个带有底部导航以及顶部导航的single view application
- IOS去掉NavigationBar底部的那条黑线
- android webkit
- Android Safe Media分析
- Android: NDK编程入门笔记