Leetcode - Integer to English Words
https://leetcode.com/problems/integer-to-english-words/
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
Example 1:
Input: 123 Output: "One Hundred Twenty Three"
Example 2:
Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five"
Example 3:
Input: 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
func numberToWords(num int) string { if num == 0 { return "Zero" } digits := []int{1000000000, 1000000, 1000, 1} nums := make([]int, 4) i := 0 for num > 0 { nums[i] = num/digits[i] num %= digits[i] i++ } result := []string{} strs := []string{"Billion", "Million", "Thousand"} for i := 0; i < len(nums)-1; i++ { if nums[i] == 0 { continue } tmp := convert(nums[i]) result = append(result, tmp...) result = append(result, strs[i]) } result = append(result, convert(nums[len(nums)-1])...) return strings.Join(result, " ") } func convert(num int) []string { if num == 0 { return []string{} } hash := map[int]string{ 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "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", } result := []string{} if num / 100 > 0 { result = append(result, hash[num/100], "Hundred") num %= 100 if num == 0 { return result } } if num / 20 > 0 { result = append(result, hash[num - (num%10)]) num %= 10 if num == 0 { return result } result = append(result, hash[num]) return result } result = append(result, hash[num]) return result }