Skip to content

Commit a120254

Browse files
authored
Merge pull request vJechsmayr#190 from jrga03/leet-code-integer-to-english-words
Add LeetCode#273 Integer to English Words
2 parents b025d11 + 4e60bf5 commit a120254

1 file changed

Lines changed: 116 additions & 0 deletions

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
/**
2+
* @param {number} num
3+
* @return {string}
4+
*/
5+
var numberToWords = function(num) {
6+
if ( !num ) return 'Zero';
7+
if ( num > 999999999999 ) return 'Number too high';
8+
9+
let word = '';
10+
if ( num < 1000 ) {
11+
word += convertLessThanAThousandToWords( num );
12+
} else {
13+
let unit;
14+
let multiplier;
15+
switch( true ) {
16+
case num >= 1e9:
17+
unit = 'Billion';
18+
multiplier = 1e9;
19+
break;
20+
case num >= 1e6:
21+
unit = 'Million';
22+
multiplier = 1e6;
23+
break;
24+
case num >= 1e3:
25+
unit = 'Thousand';
26+
multiplier = 1e3;
27+
break;
28+
default:
29+
}
30+
31+
const x = Math.floor( num / multiplier );
32+
33+
word += `${convertLessThanAThousandToWords( x )} ${unit} `;
34+
35+
const remaining = num - ( x * multiplier );
36+
if ( remaining ) {
37+
word += numberToWords( remaining );
38+
}
39+
}
40+
41+
return word.trim();
42+
};
43+
44+
/**
45+
* Converts a number less than 1000 into words
46+
* @param {number} num - A number less than 1000
47+
* @returns {string}
48+
*/
49+
var convertLessThanAThousandToWords = function(num) {
50+
if ( !num ) return ''
51+
52+
let word = '';
53+
const MAPPING = {
54+
HUNDREDS: {
55+
1: 'One Hundred',
56+
2: 'Two Hundred',
57+
3: 'Three Hundred',
58+
4: 'Four Hundred',
59+
5: 'Five Hundred',
60+
6: 'Six Hundred',
61+
7: 'Seven Hundred',
62+
8: 'Eight Hundred',
63+
9: 'Nine Hundred'
64+
},
65+
TENS: {
66+
1: 'Ten',
67+
1.1: 'Eleven',
68+
1.2: 'Twelve',
69+
1.3: 'Thirteen',
70+
1.4: 'Fourteen',
71+
1.5: 'Fifteen',
72+
1.6: 'Sixteen',
73+
1.7: 'Seventeen',
74+
1.8: 'Eighteen',
75+
1.9: 'Nineteen',
76+
2: 'Twenty',
77+
3: 'Thirty',
78+
4: 'Forty',
79+
5: 'Fifty',
80+
6: 'Sixty',
81+
7: 'Seventy',
82+
8: 'Eighty',
83+
9: 'Ninety'
84+
},
85+
ONES: {
86+
1: 'One',
87+
2: 'Two',
88+
3: 'Three',
89+
4: 'Four',
90+
5: 'Five',
91+
6: 'Six',
92+
7: 'Seven',
93+
8: 'Eight',
94+
9: 'Nine'
95+
}
96+
};
97+
98+
const hundreds = num / 100;
99+
const tens = num / 10;
100+
if ( hundreds >= 1 ) {
101+
const key = Math.floor( hundreds );
102+
word += `${MAPPING.HUNDREDS[ key ]} `;
103+
word += convertLessThanAThousandToWords( num - ( key * 100 ));
104+
} else if ( tens >= 1 ) {
105+
let key = Math.floor( tens );
106+
if ( tens < 2 ) {
107+
key = tens;
108+
}
109+
word += `${MAPPING.TENS[ key ]} `;
110+
word += convertLessThanAThousandToWords( num - ( key * 10 ) );
111+
} else {
112+
word += `${MAPPING.ONES[ num ]} `;
113+
}
114+
115+
return word.trim();
116+
}

0 commit comments

Comments
 (0)