Skip to content

Commit cc31f24

Browse files
committed
Add solution #273
1 parent 726340d commit cc31f24

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
263|[Ugly Number](./0263-ugly-number.js)|Easy|
4545
264|[Ugly Number II](./0264-ugly-number-ii.js)|Medium|
4646
268|[Missing Number](./0268-missing-number.js)|Easy|
47+
273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard|
4748
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
4849
345|[Reverse Vowels of a String](./0345-reverse-vowels-of-a-string.js)|Easy|
4950
347|[Top K Frequent Elements](./0347-top-k-frequent-elements.js)|Medium|
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 273. Integer to English Words
3+
* https://leetcode.com/problems/integer-to-english-words/
4+
* Difficulty: Hard
5+
*
6+
* Convert a non-negative integer `num` to its English words representation.
7+
*/
8+
9+
/**
10+
* @param {number} num
11+
* @return {string}
12+
*/
13+
var numberToWords = function(num) {
14+
if (num === 0) {
15+
return 'Zero';
16+
}
17+
18+
return convert(num).replace(/\s+/g, ' ').trim();
19+
};
20+
21+
const belowTen = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
22+
const belowTwenty = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
23+
const belowHundred = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
24+
25+
function convert(num) {
26+
if (num < 10) return belowTen[num];
27+
else if (num < 20) return belowTwenty[num - 10];
28+
else if (num < 100) return belowHundred[Math.floor(num / 10)] + ' ' + convert(num % 10);
29+
else if (num < 1000) return convert(Math.floor(num / 100)) + ' Hundred ' + convert(num % 100);
30+
else if (num < 1000000) return convert(Math.floor(num / 1000)) + ' Thousand ' + convert(num % 1000);
31+
else if (num < 1000000000) return convert(Math.floor(num / 1000000)) + ' Million ' + convert(num % 1000000);
32+
else return convert(Math.floor(num / 1000000000)) + ' Billion ' + convert(num % 1000000000);
33+
}

0 commit comments

Comments
 (0)