|
| 1 | +# Happy Number |
| 2 | + |
| 3 | +Tags: Hash Table, Math, Easy |
| 4 | + |
| 5 | +## Question |
| 6 | + |
| 7 | +- leetcode: [Happy Number](https://leetcode.com/problems/happy-number/) |
| 8 | +- lintcode: [Happy Number](http://www.lintcode.com/en/problem/happy-number/) |
| 9 | + |
| 10 | +### Problem Statement |
| 11 | + |
| 12 | +Write an algorithm to determine if a number is "happy". |
| 13 | + |
| 14 | +A happy number is a number defined by the following process: Starting with any |
| 15 | +positive integer, replace the number by the sum of the squares of its digits, |
| 16 | +and repeat the process until the number equals 1 (where it will stay), or it |
| 17 | +loops endlessly in a cycle which does not include 1. Those numbers for which |
| 18 | +this process ends in 1 are happy numbers. |
| 19 | + |
| 20 | +**Example: **19 is a happy number |
| 21 | + |
| 22 | + * 12 \+ 92 = 82 |
| 23 | + * 82 \+ 22 = 68 |
| 24 | + * 62 \+ 82 = 100 |
| 25 | + * 12 \+ 02 \+ 02 = 1 |
| 26 | + |
| 27 | +**Credits:** |
| 28 | +Special thanks to [@mithmatt](https://leetcode.com/discuss/user/mithmatt) and |
| 29 | +[@ts](https://leetcode.com/discuss/user/ts) for adding this problem and |
| 30 | +creating all test cases. |
| 31 | + |
| 32 | +## 题解 |
| 33 | + |
| 34 | +根据指定运算规则判断输入整数是否为『happy number』,容易推断得知最终要么能求得1,要么为环形队列不断循环。 |
| 35 | +第一种情况容易判断,第二种情况即判断得到的数是否为环形队列,也就是说是否重复出现,这种场景使用哈希表轻易解决。 |
| 36 | + |
| 37 | +### Java |
| 38 | + |
| 39 | +```java |
| 40 | +public class Solution { |
| 41 | + public boolean isHappy(int n) { |
| 42 | + if (n < 0) return false; |
| 43 | + |
| 44 | + Set<Integer> set = new HashSet<Integer>(); |
| 45 | + set.add(n); |
| 46 | + while (n != 1) { |
| 47 | + n = digitsSquareSum(n); |
| 48 | + if (n == 1) { |
| 49 | + return true; |
| 50 | + } else if (set.contains(n)) { |
| 51 | + return false; |
| 52 | + } else { |
| 53 | + set.add(n); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return true; |
| 58 | + } |
| 59 | + |
| 60 | + private int digitsSquareSum(int n) { |
| 61 | + int sum = 0; |
| 62 | + for (; n > 0; n /= 10) { |
| 63 | + sum += (n % 10) * (n % 10); |
| 64 | + } |
| 65 | + return sum; |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
| 69 | + |
| 70 | +### 源码分析 |
| 71 | + |
| 72 | +辅助方法计算数字平方和。 |
| 73 | + |
| 74 | +### 复杂度分析 |
| 75 | + |
| 76 | +有限迭代次数一定终止,时间和空间复杂度均为 $$O(1)$$. |
0 commit comments