Skip to content

Commit 6732085

Browse files
authored
feat: add golang solution to lc problem: No.0202 (#878)
No.0202.Happy Number
1 parent 16db48b commit 6732085

File tree

3 files changed

+50
-30
lines changed

3 files changed

+50
-30
lines changed

solution/0200-0299/0202.Happy Number/README.md

+20
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,26 @@ public:
132132
};
133133
```
134134
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+
135155
### **TypeScript**
136156

137157
```ts

solution/0200-0299/0202.Happy Number/README_EN.md

+20
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,26 @@ public:
116116
};
117117
```
118118
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+
119139
### **TypeScript**
120140

121141
```ts
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,15 @@
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
135
}
14-
return sum
6+
return n == 1
157
}
168

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
3413
}
14+
return
3515
}

0 commit comments

Comments
 (0)