diff --git a/Algorithms/202. Happy Number/202. Happy Number.go b/Algorithms/202. Happy Number/202. Happy Number.go new file mode 100644 index 00000000..adf6a0cd --- /dev/null +++ b/Algorithms/202. Happy Number/202. Happy Number.go @@ -0,0 +1,28 @@ +package leetcode + +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 + } else { + record[res] = res + num = res + res = 0 + continue + } + } else { + return false + } + } +} diff --git a/Algorithms/202. Happy Number/202. Happy Number_test.go b/Algorithms/202. Happy Number/202. Happy Number_test.go new file mode 100644 index 00000000..f4963e98 --- /dev/null +++ b/Algorithms/202. Happy Number/202. Happy Number_test.go @@ -0,0 +1,47 @@ +package leetcode + +import ( + "fmt" + "testing" +) + +type question202 struct { + para202 + ans202 +} + +// para 是参数 +// one 代表第一个参数 +type para202 struct { + one int +} + +// ans 是答案 +// one 代表第一个答案 +type ans202 struct { + one bool +} + +func Test_Problem202(t *testing.T) { + + qs := []question202{ + + question202{ + para202{202}, + ans202{false}, + }, + + question202{ + para202{19}, + ans202{true}, + }, + } + + fmt.Printf("------------------------Leetcode Problem 202------------------------\n") + + for _, q := range qs { + _, p := q.ans202, q.para202 + fmt.Printf("【input】:%v 【output】:%v\n", p, isHappy(p.one)) + } + fmt.Printf("\n\n\n") +} diff --git a/Algorithms/202. Happy Number/README.md b/Algorithms/202. Happy Number/README.md new file mode 100644 index 00000000..eb22b171 --- /dev/null +++ b/Algorithms/202. Happy Number/README.md @@ -0,0 +1,26 @@ +# [202. Happy Number](https://leetcode.com/problems/happy-number/) + +## 题目 + +Write an algorithm to determine if a number 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, and 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 numbers. + +Example 1: + +```c +Input: 19 +Output: true +Explanation: +12 + 92 = 82 +82 + 22 = 68 +62 + 82 = 100 +12 + 02 + 02 = 1 +``` + +## 题目大意 + +判断一个数字是否是“快乐数字”,“快乐数字”的定义是,不断的把这个数字的每个数字的平方和加起来,反复的加,最终如果能有结果是 1,则是“快乐数字”,如果不能得到一,出现了循环,则输出 false。 + + +