diff --git a/problems/202-happy-number/README.md b/problems/202-happy-number/README.md new file mode 100644 index 0000000..b9c848a --- /dev/null +++ b/problems/202-happy-number/README.md @@ -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 diff --git a/problems/202-happy-number/main.go b/problems/202-happy-number/main.go new file mode 100644 index 0000000..e1851c9 --- /dev/null +++ b/problems/202-happy-number/main.go @@ -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 + } + } +}