|
| 1 | +/** |
| 2 | + * @param {number} num |
| 3 | + * @return {string} |
| 4 | + */ |
| 5 | + |
| 6 | +// my own solution |
| 7 | +var numberToWords = function(num) { |
| 8 | + var dict = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', |
| 9 | + 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', |
| 10 | + 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', |
| 11 | + 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', |
| 12 | + 19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', |
| 13 | + 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', |
| 14 | + 90: 'Ninety'}; |
| 15 | + var str = ''; |
| 16 | + |
| 17 | + if (num === 0) { |
| 18 | + return 'Zero'; |
| 19 | + } |
| 20 | + |
| 21 | + for (var i = 9; i >= 0;) { |
| 22 | + var most = Math.floor(num / Math.pow(10, i)); |
| 23 | + num = num % Math.pow(10, i); |
| 24 | + |
| 25 | + if (i === 9 && most > 0) { |
| 26 | + str += dict[most] + ' Billion '; |
| 27 | + } |
| 28 | + |
| 29 | + if (i === 6 && most > 0) { |
| 30 | + str += threeDigits(most, dict) + ' Million '; |
| 31 | + } |
| 32 | + |
| 33 | + if (i === 3 && most > 0) { |
| 34 | + str += threeDigits(most, dict) + ' Thousand '; |
| 35 | + } |
| 36 | + |
| 37 | + if (i === 0 && most > 0) { |
| 38 | + str += threeDigits(most, dict); |
| 39 | + } |
| 40 | + |
| 41 | + if (num === 0) { |
| 42 | + str = str.trim(); |
| 43 | + break; |
| 44 | + } |
| 45 | + |
| 46 | + i -= 3; |
| 47 | + } |
| 48 | + |
| 49 | + return str; |
| 50 | +}; |
| 51 | + |
| 52 | +var threeDigits = function(num, dict) { |
| 53 | + var hundred = 0; |
| 54 | + var rem = 0; |
| 55 | + var str = ''; |
| 56 | + |
| 57 | + if (num === 0) { |
| 58 | + return ''; |
| 59 | + } else if (num < 100) { |
| 60 | + str = twoDigits(num, dict); |
| 61 | + } else { |
| 62 | + hundred = Math.floor(num / 100); |
| 63 | + str = dict[hundred] + ' Hundred'; |
| 64 | + rem = num % 100; |
| 65 | + |
| 66 | + if (rem <= 10 && rem > 0) { |
| 67 | + str += ' ' + dict[rem]; |
| 68 | + } else if (rem > 10) { |
| 69 | + str += ' ' + twoDigits(rem, dict); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return str; |
| 74 | +}; |
| 75 | + |
| 76 | +var twoDigits = function twoDigits(num, dict) { |
| 77 | + var str = ''; |
| 78 | + var least = Math.floor(num % 10); |
| 79 | + var most = num - least; |
| 80 | + |
| 81 | + if (least === 0 || num <= 20) { |
| 82 | + str += dict[num]; |
| 83 | + } else { |
| 84 | + str += dict[most] + ' ' + dict[least]; |
| 85 | + } |
| 86 | + |
| 87 | + return str; |
| 88 | +} |
0 commit comments