Skip to content

Commit a4dc714

Browse files
committed
add Happy Number
1 parent fdc6c25 commit a4dc714

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

zh-hans/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@
9999
* [Update Bits](math_and_bit_manipulation/update_bits.md)
100100
* [Fast Power](math_and_bit_manipulation/fast_power.md)
101101
* [Hash Function](math_and_bit_manipulation/hash_function.md)
102+
* [Happy Number](math_and_bit_manipulation/happy_number.md)
102103
* [Count 1 in Binary](math_and_bit_manipulation/count_1_in_binary.md)
103104
* [Fibonacci](math_and_bit_manipulation/fibonacci.md)
104105
* [A plus B Problem](math_and_bit_manipulation/a_plus_b_problem.md)
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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

Comments
 (0)