Skip to content

Commit d375cf5

Browse files
committed
add 202 solution
1 parent 245bfab commit d375cf5

File tree

2 files changed

+57
-7
lines changed

2 files changed

+57
-7
lines changed

src/0202.Happy-Number/Solution.go

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,35 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
// 快慢指针
4+
func isHappy(n int) bool {
5+
slow, fast := n, squareSum(n)
6+
for fast != 1 && slow != fast {
7+
slow = squareSum(slow)
8+
fast = squareSum(squareSum(fast))
9+
}
10+
return fast == 1
11+
}
12+
13+
// 利用 map 判断
14+
func isHappy2(n int) bool {
15+
seen := make(map[int]int)
16+
for {
17+
if _, ok := seen[n]; ok {
18+
return true
19+
}
20+
seen[n] = -1
21+
n = squareSum(n)
22+
if n == 1 {
23+
return true
24+
}
25+
}
26+
}
27+
28+
func squareSum(m int) int {
29+
sum := 0
30+
for m != 0 {
31+
sum += (m % 10) * (m % 10)
32+
m /= 10
33+
}
34+
return sum
535
}

src/0202.Happy-Number/Solution_test.go

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,38 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
13+
inputs int
1414
expect bool
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase", 19, true},
1917
}
2018

2119
// 开始测试
2220
for i, c := range cases {
2321
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
24-
got := Solution(c.inputs)
22+
got := isHappy(c.inputs)
23+
if !reflect.DeepEqual(got, c.expect) {
24+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
25+
c.expect, got, c.inputs)
26+
}
27+
})
28+
}
29+
}
30+
31+
func TestSolution2(t *testing.T) {
32+
// 测试用例
33+
cases := []struct {
34+
name string
35+
inputs int
36+
expect bool
37+
}{
38+
{"TestCase", 19, true},
39+
}
40+
41+
// 开始测试
42+
for i, c := range cases {
43+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
44+
got := isHappy2(c.inputs)
2545
if !reflect.DeepEqual(got, c.expect) {
2646
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
2747
c.expect, got, c.inputs)

0 commit comments

Comments
 (0)