Skip to content

Commit ebedde4

Browse files
committed
Solve problem '202) happy number'
1 parent c63cce6 commit ebedde4

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
Write an algorithm to determine if a number `n` is happy.
2+
3+
A **happy number** is a number defined by the following process:
4+
5+
- Starting with any positive integer, replace the number by the sum of the squares of its digits.
6+
- Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
7+
- Those numbers for which this process **ends in 1** are happy.
8+
9+
Return `true` if `n` _is a happy number, and_ `false` if not.
10+
11+
**Example 1:**
12+
13+
```
14+
Input: n = 19
15+
Output: true
16+
Explanation:
17+
12 + 92 = 82
18+
82 + 22 = 68
19+
62 + 82 = 100
20+
12 + 02 + 02 = 1
21+
```
22+
23+
**Example 2:**
24+
25+
```
26+
Input: n = 2
27+
Output: false
28+
```
29+
30+
**Constraints:**
31+
32+
- 1 <= n <= 2^31 - 1

problems/202-happy-number/main.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func main() {
6+
fmt.Println(isHappy(19))
7+
fmt.Println(isHappy(2))
8+
}
9+
10+
func isHappy(n int) bool {
11+
if n == 0 {
12+
return false
13+
}
14+
res := 0
15+
num := n
16+
record := map[int]int{}
17+
for {
18+
for num != 0 {
19+
res += (num % 10) * (num % 10)
20+
num = num / 10
21+
}
22+
if _, ok := record[res]; !ok {
23+
if res == 1 {
24+
return true
25+
}
26+
record[res] = res
27+
num = res
28+
res = 0
29+
continue
30+
} else {
31+
return false
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)