diff --git a/problems/happy-number/happy_number.go b/problems/happy-number/happy_number.go index 2bce4663d..4b470ebe6 100644 --- a/problems/happy-number/happy_number.go +++ b/problems/happy-number/happy_number.go @@ -1 +1,16 @@ package happy_number + +func isHappy(n int) bool { + m := make(map[int]bool) + for n != 1 && !m[n] { + m[n] = true + sum := 0 + for n > 0 { + x := n % 10 + sum += x * x + n /= 10 + } + n = sum + } + return n == 1 +} diff --git a/problems/happy-number/happy_number_test.go b/problems/happy-number/happy_number_test.go index 2bce4663d..1baca9617 100644 --- a/problems/happy-number/happy_number_test.go +++ b/problems/happy-number/happy_number_test.go @@ -1 +1,31 @@ package happy_number + +import "testing" + +type caseType struct { + input int + expected bool +} + +func TestIsHappy(t *testing.T) { + tests := [...]caseType{ + { + input: 19, + expected: true, + }, + { + input: 1, + expected: true, + }, + { + input: 0, + expected: false, + }, + } + for _, tc := range tests { + output := isHappy(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}