New Go
This commit is contained in:
59
BasicSyntax/prime/toeng.go
Normal file
59
BasicSyntax/prime/toeng.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func numberToWords(n int) string {
|
||||
if n < 0 || n >= 1000 {
|
||||
return "ERR"
|
||||
}
|
||||
|
||||
ones := []string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
|
||||
teens := []string{"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
|
||||
"sixteen", "seventeen", "eighteen", "nineteen"}
|
||||
tens := []string{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}
|
||||
|
||||
words := []string{}
|
||||
|
||||
// 百位
|
||||
if n >= 100 {
|
||||
words = append(words, ones[n/100]+" hundred")
|
||||
n %= 100
|
||||
if n != 0 {
|
||||
words = append(words, "and")
|
||||
}
|
||||
}
|
||||
|
||||
// 十位和个位
|
||||
if n >= 20 {
|
||||
if n%10 != 0 {
|
||||
words = append(words, tens[n/10]+"-"+ones[n%10])
|
||||
} else {
|
||||
words = append(words, tens[n/10])
|
||||
}
|
||||
} else if n >= 10 {
|
||||
words = append(words, teens[n-10])
|
||||
} else if n > 0 {
|
||||
words = append(words, ones[n])
|
||||
} else if len(words) == 0 { // n == 0
|
||||
words = append(words, "zero")
|
||||
}
|
||||
|
||||
return joinWords(words)
|
||||
}
|
||||
|
||||
func joinWords(words []string) string {
|
||||
res := ""
|
||||
for i, w := range words {
|
||||
if i > 0 {
|
||||
res += " "
|
||||
}
|
||||
res += w
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func main() {
|
||||
var n int
|
||||
fmt.Scan(&n)
|
||||
fmt.Println(numberToWords(n))
|
||||
}
|
||||
Reference in New Issue
Block a user