-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathnumber_in_english.go
108 lines (92 loc) · 2.08 KB
/
number_in_english.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package strings
import (
"strings"
)
const (
zero = 0
ten = 10
hundred = 100
thousand = 1000
million = 1000000
billion = 1000000000
)
var digits = map[int]string{
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Seven",
8: "Eight",
9: "Nine",
ten: "Ten",
11: "Eleven",
12: "Twelve",
13: "Thirteen",
14: "Fourteen",
15: "Fifteen",
16: "Sixteen",
17: "Seventeen",
18: "Eighteen",
19: "Nineteen",
20: "Twenty",
30: "Thirty",
40: "Forty",
50: "Fifty",
60: "Sixty",
70: "Seventy",
80: "Eighty",
90: "Ninety",
hundred: "Hundred",
thousand: "Thousand",
million: "Million",
billion: "Billion",
}
// NumberInEnglish solves the problem in O(1) time and O(1) space.
func NumberInEnglish(num int) string {
var output, eachOutput string
if num == zero {
return "Zero"
}
num, eachOutput = outputIfLarger(num, billion, digits[billion])
output += eachOutput
num, eachOutput = outputIfLarger(num, million, digits[million])
output += eachOutput
num, eachOutput = outputIfLarger(num, thousand, digits[thousand])
output += eachOutput
eachOutput = threeDigitWord(num)
output += eachOutput
output = strings.ReplaceAll(output, " ", " ")
return strings.TrimSpace(output)
}
func outputIfLarger(num, unit int, word string) (int, string) {
output := ""
if times := howMany(num, unit); times != -1 {
output = threeDigitWord(times) + " " + word + " "
num -= times * unit
}
return num, output
}
func threeDigitWord(num int) string {
output := ""
if hundreds := howMany(num, hundred); hundreds != -1 {
output += digits[hundreds] + " Hundred "
num -= hundreds * hundred
}
if v, ok := digits[num]; ok {
return output + v
}
if tens := howMany(num, ten); tens != -1 {
output += digits[tens*ten] + " "
num -= tens * ten
}
output += digits[num]
return output
}
func howMany(num, level int) int {
if num < level {
return -1
}
return int(float64(num / level))
}