Skip to content

Commit 3f206ad

Browse files
authored
update js solution for lc problem No. 0273
1 parent 3a46cbc commit 3f206ad

File tree

1 file changed

+52
-0
lines changed
  • solution/0200-0299/0273.Integer to English Words

1 file changed

+52
-0
lines changed

solution/0200-0299/0273.Integer to English Words/README_EN.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,58 @@ class Solution {
347347

348348
<!-- tabs:end -->
349349

350+
<!-- tabs:start -->
351+
352+
#### JavaScript
353+
354+
```js
355+
/**
356+
* @param {number} num
357+
* @return {string}
358+
*/
359+
const lessThanTwenty = [
360+
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
361+
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"
362+
];
363+
364+
const tens = [
365+
"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
366+
];
367+
368+
const thousands = [
369+
"", "Thousand", "Million", "Billion"
370+
];
371+
372+
function numberToWords(num) {
373+
if (num === 0) return "Zero";
374+
375+
let result = "";
376+
let i = 0;
377+
378+
while (num > 0) {
379+
if (num % 1000 !== 0) {
380+
result = helper(num % 1000) + thousands[i] + " " + result;
381+
}
382+
num = Math.floor(num / 1000);
383+
i++;
384+
}
385+
386+
return result.trim();
387+
}
388+
389+
function helper(num) {
390+
if (num === 0) return "";
391+
else if (num < 20) return lessThanTwenty[num] + " ";
392+
else if (num < 100) return tens[Math.floor(num / 10)] + " " + helper(num % 10);
393+
else return lessThanTwenty[Math.floor(num / 100)] + " Hundred " + helper(num % 100);
394+
}
395+
```
396+
397+
<!-- tabs:end -->
398+
399+
350400
<!-- solution:end -->
351401

402+
403+
352404
<!-- problem:end -->

0 commit comments

Comments
 (0)