题解 | #学英语#
学英语
http://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
func main() {
// map: key = num, value = word
m := make(map[int]string)
m[1] = "one"
m[2] = "two"
m[3] = "three"
m[4] = "four"
m[5] = "five"
m[6] = "six"
m[7] = "seven"
m[8] = "eight"
m[9] = "nine"
m[10] = "ten"
m[11] = "eleven"
m[12] = "twelve"
m[13] = "thirteen"
m[14] = "fourteen"
m[15] = "fifteen"
m[16] = "sixteen"
m[17] = "seventeen"
m[18] = "eighteen"
m[19] = "ninteen"
m[20] = "twenty"
m[30] = "thirty"
m[40] = "forty"
m[50] = "fifty"
m[60] = "sixty"
m[70] = "seventy"
m[80] = "eighty"
m[90] = "ninety"
// input
inputReader := bufio.NewReader(os.Stdin)
for {
// handle input
input, err := inputReader.ReadString('\n')
if err == io.EOF {
break
}
input = strings.Trim(input, "\r\n")
if input == "0" {
fmt.Println(0)
continue
}
// 从右边开始,每三个数字为一组,split -> arr
arr := make([]int, 0)
if len(input) < 2 { // 只有一位
input0, _ := strconv.Atoi(string(input[0]))
arr = append(arr, input0)
} else if len(input) > 1 { // 十位 + 个位
input1, _ := strconv.Atoi(string(input[len(input)-2:]))
arr = append(arr, input1)
}
if len(input) > 2 { // 百位
input2, _ := strconv.Atoi(string(input[len(input)-3]))
arr = append(arr, input2)
}
if len(input) == 4 { // 最高千位
input3, _ := strconv.Atoi(string(input[0]))
arr = append(arr, input3)
}
if len(input) > 4 { // 万位 + 千位
input4, _ := strconv.Atoi(string(input[len(input)-5 : len(input)-3]))
arr = append(arr, input4)
}
if len(input) > 5 { // 十万位
input5, _ := strconv.Atoi(string(input[len(input)-6]))
arr = append(arr, input5)
}
if len(input) == 7 { // 百万位
input6, _ := strconv.Atoi(string(input[0]))
arr = append(arr, input6)
}
// 从右边开始,加word
res := ""
for i := 0; i < len(arr); i++ {
if arr[i] == 0 {
continue
}
if i == 0 { // 十位 + 个位
if arr[i] < 20 {
res = m[arr[i]]
} else {
gewei := arr[i] % 10
shiwei := arr[i] - gewei
res = m[shiwei] + " " + m[gewei]
}
}
if i == 1 { // 百位
if arr[i] == 0 {
continue
}
if arr[0] == 0 {
res = m[arr[i]] + " hundred" + res
} else {
res = m[arr[i]] + " hundred and " + res
}
}
if i == 2 { // 万位 + 千位
if arr[i] == 0 {
continue
}
if arr[i] < 20 {
res = m[arr[i]] + " thousand " + res
} else {
gewei := arr[i] % 10
shiwei := arr[i] - gewei
if gewei == 0 {
res = m[shiwei] + " thousand " + res
} else {
res = m[shiwei] + " " + m[gewei] + " thousand " + res
}
}
}
if i == 3 { // 十万位
if arr[2] == 0 {
res = m[arr[i]] + " hundred " + res
} else {
res = m[arr[i]] + " hundred and " + res
}
}
if i == 4 { // 百万位
res = m[arr[i]] + " million " + res
}
}
fmt.Println(res)
}
}