Skip to content

Commit e216ed4

Browse files
authored
Merge pull request #153 from brenobaptista/suggestion-202
Suggestion 202
2 parents 7c7f09d + 1eb35d8 commit e216ed4

File tree

2 files changed

+34
-19
lines changed

2 files changed

+34
-19
lines changed
Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
11
package leetcode
22

3-
func isHappy(n int) bool {
4-
if n == 0 {
5-
return false
3+
func getSquareOfDigits(n int) int {
4+
squareOfDigits := 0
5+
temporary := n
6+
7+
for temporary != 0 {
8+
remainder := temporary % 10
9+
squareOfDigits += remainder * remainder
10+
temporary /= 10
611
}
7-
res := 0
8-
num := n
12+
13+
return squareOfDigits
14+
}
15+
16+
func isHappy(n int) bool {
917
record := map[int]int{}
10-
for {
11-
for num != 0 {
12-
res += (num % 10) * (num % 10)
13-
num = num / 10
14-
}
15-
if _, ok := record[res]; !ok {
16-
if res == 1 {
17-
return true
18+
19+
for n != 1 {
20+
record[n] = n
21+
22+
n = getSquareOfDigits(n)
23+
24+
for _, previous := range record {
25+
if n == previous {
26+
return false
1827
}
19-
record[res] = res
20-
num = res
21-
res = 0
22-
continue
23-
} else {
24-
return false
2528
}
2629
}
30+
31+
return true
2732
}

leetcode/0202.Happy-Number/202. Happy Number_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@ func Test_Problem202(t *testing.T) {
3535
para202{19},
3636
ans202{true},
3737
},
38+
39+
{
40+
para202{2},
41+
ans202{false},
42+
},
43+
44+
{
45+
para202{3},
46+
ans202{false},
47+
},
3848
}
3949

4050
fmt.Printf("------------------------Leetcode Problem 202------------------------\n")

0 commit comments

Comments
 (0)