File tree 3 files changed +50
-30
lines changed
solution/0200-0299/0202.Happy Number
3 files changed +50
-30
lines changed Original file line number Diff line number Diff line change @@ -132,6 +132,26 @@ public:
132
132
};
133
133
```
134
134
135
+ ### **Go**
136
+
137
+ ```go
138
+ func isHappy(n int) bool {
139
+ m := make(map[int]bool)
140
+ for n != 1 && !m[n] {
141
+ n, m[n] = getSum(n), true
142
+ }
143
+ return n == 1
144
+ }
145
+
146
+ func getSum(n int) (sum int) {
147
+ for n > 0 {
148
+ sum += (n % 10) * (n % 10)
149
+ n = n / 10
150
+ }
151
+ return
152
+ }
153
+ ```
154
+
135
155
### ** TypeScript**
136
156
137
157
``` ts
Original file line number Diff line number Diff line change @@ -116,6 +116,26 @@ public:
116
116
};
117
117
```
118
118
119
+ ### **Go**
120
+
121
+ ```go
122
+ func isHappy(n int) bool {
123
+ m := make(map[int]bool)
124
+ for n != 1 && !m[n] {
125
+ n, m[n] = getSum(n), true
126
+ }
127
+ return n == 1
128
+ }
129
+
130
+ func getSum(n int) (sum int) {
131
+ for n > 0 {
132
+ sum += (n % 10) * (n % 10)
133
+ n = n / 10
134
+ }
135
+ return
136
+ }
137
+ ```
138
+
119
139
### ** TypeScript**
120
140
121
141
``` ts
Original file line number Diff line number Diff line change 1
- var resultMap map [int ]bool
2
-
3
- func init () {
4
- resultMap = make (map [int ]bool )
5
- }
6
-
7
- func calculate (num int ) int {
8
- sum := 0
9
- for num > 0 {
10
- k := num % 10
11
- sum += k * k
12
- num = num / 10
1
+ func isHappy (n int ) bool {
2
+ m := make (map [int ]bool )
3
+ for n != 1 && ! m [n ] {
4
+ n , m [n ] = getSum (n ), true
13
5
}
14
- return sum
6
+ return n == 1
15
7
}
16
8
17
- func isHappy (n int ) bool {
18
- tmpMap := make (map [int ]bool )
19
- for ; ; n = calculate (n ) {
20
- f , ok := resultMap [n ]
21
- if f || n == 1 {
22
- for k := range tmpMap {
23
- resultMap [k ] = true
24
- }
25
- return true
26
- }
27
- if (! f && ok ) || tmpMap [n ] {
28
- for k := range tmpMap {
29
- resultMap [k ] = false
30
- }
31
- return false
32
- }
33
- tmpMap [n ] = true
9
+ func getSum (n int ) (sum int ) {
10
+ for n > 0 {
11
+ sum += (n % 10 ) * (n % 10 )
12
+ n = n / 10
34
13
}
14
+ return
35
15
}
You can’t perform that action at this time.
0 commit comments