Skip to content

Commit

Permalink
Solve problem '202) happy number'
Browse files Browse the repository at this point in the history
  • Loading branch information
ozantopal committed Jan 22, 2022
1 parent c63cce6 commit ebedde4
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
32 changes: 32 additions & 0 deletions problems/202-happy-number/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
Write an algorithm to determine if a number `n` 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.
- 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.

Return `true` if `n` _is a happy number, and_ `false` if not.

**Example 1:**

```
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
```

**Example 2:**

```
Input: n = 2
Output: false
```

**Constraints:**

- 1 <= n <= 2^31 - 1
34 changes: 34 additions & 0 deletions problems/202-happy-number/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import "fmt"

func main() {
fmt.Println(isHappy(19))
fmt.Println(isHappy(2))
}

func isHappy(n int) bool {
if n == 0 {
return false
}
res := 0
num := n
record := map[int]int{}
for {
for num != 0 {
res += (num % 10) * (num % 10)
num = num / 10
}
if _, ok := record[res]; !ok {
if res == 1 {
return true
}
record[res] = res
num = res
res = 0
continue
} else {
return false
}
}
}

0 comments on commit ebedde4

Please sign in to comment.