# 2022-01-09：整数转换英文表示。将非负整数 num 转换为其对应的英文表示。 示例 1： 输入：num = 123， 输出：“One Hundred Twenty Three“。 力扣273。

2022-01-09：整数转换英文表示。将非负整数 num 转换为其对应的英文表示。

``````package main

import (
"fmt"
"math"
"strings"
)

func main() {
num := 123
ret := numberToWords(num)
fmt.Println(ret)
}

func num1To19(num int) string {
if num < 1 || num > 19 {
return ""
}
names := []string{"One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine ", "Ten ",
"Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen", "Eighteen ",
"Nineteen "}
return names[num-1]
}

func num1To99(num int) string {
if num < 1 || num > 99 {
return ""
}
if num < 20 {
return num1To19(num)
}
high := num / 10
tyNames := []string{"Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety "}
return tyNames[high-2] + num1To19(num%10)
}

func num1To999(num int) string {
if num < 1 || num > 999 {
return ""
}
if num < 100 {
return num1To99(num)
}
high := num / 100
return num1To19(high) + "Hundred " + num1To99(num%100)
}

func numberToWords(num int) string {
if num == 0 {
return "Zero"
}
res := ""
if num < 0 {
res = "Negative "
}
if num == math.MinInt64 {
res += "Two Billion "
num %= -2000000000
}
num = Abs(num)
high := 1000000000
highIndex := 0
names := []string{"Billion ", "Million ", "Thousand ", ""}
for num != 0 {
cur := num / high
num %= high
if cur != 0 {
res += num1To999(cur)
res += names[highIndex]
}
high /= 1000
highIndex++
}
return strings.Trim(res, " ")
}

func Abs(a int) int {
if a < 0 {
return -a
} else {
return a
}
}
``````

THE END