File tree Expand file tree Collapse file tree 1 file changed +24
-19
lines changed
leetcode/0202.Happy-Number Expand file tree Collapse file tree 1 file changed +24
-19
lines changed Original file line number Diff line number Diff line change 1
1
package leetcode
2
2
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
6
11
}
7
- res := 0
8
- num := n
12
+
13
+ return squareOfDigits
14
+ }
15
+
16
+ func isHappy (n int ) bool {
9
17
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
18
27
}
19
- record [res ] = res
20
- num = res
21
- res = 0
22
- continue
23
- } else {
24
- return false
25
28
}
26
29
}
30
+
31
+ return true
27
32
}
You can’t perform that action at this time.
0 commit comments