Skip to content

Latest commit

 

History

History
45 lines (36 loc) · 1.05 KB

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

File metadata and controls

45 lines (36 loc) · 1.05 KB

中文数字转阿拉伯数字

字符串处理问题,需要考虑 万亿十万 等情况。

package main

import "fmt"

func main() {
	fmt.Println(solution("二百"))
}

func solution(chineseNum string) int {
	res, part, temp := 0, 0, 0
	numberDict := map[string]int{"零": 0, "一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9}
	unitDict := map[string]int{"十": 10, "百": 100, "千": 1000}
	largeUnitDict := map[string]int{"万": 10000}      // “十万”
	largerUnitDict := map[string]int{"亿": 100000000} // “万亿”
	for _, ch := range chineseNum {
		if val, ok := numberDict[string(ch)]; ok {
			temp = val
		} else if val, ok := unitDict[string(ch)]; ok {
			part += temp * val
			temp = 0
		} else if val, ok := largeUnitDict[string(ch)]; ok {
			part += temp
			temp = 0
			part *= val
		} else if val, ok := largerUnitDict[string(ch)]; ok {
			part += temp
			temp = 0
			part *= val
			res += part // 亿之前的数直接加到 res 里
			part = 0
		}

	}
	res += part + temp
	return res
}