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"
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 | 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 } |