|
3 | 3 | *@return {string} |
4 | 4 | */ |
5 | 5 |
|
6 | | -// my own solution |
| 6 | +// my own solution |
7 | 7 | varnumberToWords=function(num){ |
8 | 8 | vardict={1:'One',2:'Two',3:'Three',4:'Four',5:'Five', |
9 | 9 | 6:'Six',7:'Seven',8:'Eight',9:'Nine',10:'Ten', |
@@ -86,3 +86,44 @@ var twoDigits = function twoDigits(num, dict) { |
86 | 86 |
|
87 | 87 | returnstr; |
88 | 88 | } |
| 89 | + |
| 90 | + |
| 91 | +// a more concise way |
| 92 | +varzeroToTwenty=['','One','Two','Three','Four','Five', |
| 93 | +'Six','Seven','Eight','Nine','Ten','Eleven','Twelve', |
| 94 | +'Thirteen','Fourteen','Fifteen','Sixteen','Seventeen', |
| 95 | +'Eighteen','Nineteen','Twenty']; |
| 96 | +vartwentyToNinety=['','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']; |
| 97 | +varthousand=['','Thousand','Million','Billion']; |
| 98 | + |
| 99 | +varnumberToWords=function(num){ |
| 100 | +varstr=''; |
| 101 | + |
| 102 | +if(num===0){ |
| 103 | +return'Zero'; |
| 104 | +} |
| 105 | + |
| 106 | +for(vari=0;num>0;i++){ |
| 107 | +varh=num%1000; |
| 108 | +if(h>0){// in case 1,000,000 |
| 109 | +str=helper(h)+thousand[i]+' '+str; |
| 110 | +} |
| 111 | +num=Math.floor(num/1000); |
| 112 | +} |
| 113 | + |
| 114 | +returnstr.trim(); |
| 115 | +}; |
| 116 | + |
| 117 | +functionhelper(num){ |
| 118 | +if(num===0){ |
| 119 | +return''; |
| 120 | +}elseif(num<=20){ |
| 121 | +returnzeroToTwenty[num]+' '; |
| 122 | +}elseif(num<100){ |
| 123 | +varh=Math.floor(num/10); |
| 124 | +returntwentyToNinety[h-1]+' '+helper(num%10); |
| 125 | +}else{ |
| 126 | +varh=Math.floor(num/100); |
| 127 | +returnzeroToTwenty[h]+' Hundred '+helper(num%100); |
| 128 | +} |
| 129 | +} |