File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
problems/202-happy-number Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments