Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9f18b12

Browse files
author
Shuo
authored
Merge pull request #394 from openset/develop
Add: Happy Number
2 parents 438afdf + c04a3a9 commit 9f18b12

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,16 @@
11
package happy_number
2+
3+
func isHappy(n int) bool {
4+
m := make(map[int]bool)
5+
for n != 1 && !m[n] {
6+
m[n] = true
7+
sum := 0
8+
for n > 0 {
9+
x := n % 10
10+
sum += x * x
11+
n /= 10
12+
}
13+
n = sum
14+
}
15+
return n == 1
16+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package happy_number
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input int
7+
expected bool
8+
}
9+
10+
func TestIsHappy(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: 19,
14+
expected: true,
15+
},
16+
{
17+
input: 1,
18+
expected: true,
19+
},
20+
{
21+
input: 0,
22+
expected: false,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := isHappy(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /