Skip to content

Commit b5fc22b

Browse files
Create 中文数字转阿拉伯数字.md
1 parent b73305f commit b5fc22b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

中文数字转阿拉伯数字.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# 中文数字转阿拉伯数字
2+
3+
4+
5+
字符串处理问题,需要考虑 `万亿``十万` 等情况。
6+
7+
```go
8+
package main
9+
10+
import "fmt"
11+
12+
func main() {
13+
fmt.Println(solution("二百"))
14+
}
15+
16+
func solution(chineseNum string) int {
17+
res, part, temp := 0, 0, 0
18+
numberDict := map[string]int{"": 0, "": 1, "": 2, "": 3, "": 4, "": 5, "": 6, "": 7, "": 8, "": 9}
19+
unitDict := map[string]int{"": 10, "": 100, "": 1000}
20+
largeUnitDict := map[string]int{"": 10000} // “十万”
21+
largerUnitDict := map[string]int{"亿": 100000000} // “万亿”
22+
for _, ch := range chineseNum {
23+
if val, ok := numberDict[string(ch)]; ok {
24+
temp = val
25+
} else if val, ok := unitDict[string(ch)]; ok {
26+
part += temp * val
27+
temp = 0
28+
} else if val, ok := largeUnitDict[string(ch)]; ok {
29+
part += temp
30+
temp = 0
31+
part *= val
32+
} else if val, ok := largerUnitDict[string(ch)]; ok {
33+
part += temp
34+
temp = 0
35+
part *= val
36+
res += part // 亿之前的数直接加到 res 里
37+
part = 0
38+
}
39+
40+
}
41+
res += part + temp
42+
return res
43+
}
44+
```
45+

0 commit comments

Comments
 (0)