@@ -32,58 +32,47 @@ const map = {
3232 90 : 'Ninety' ,
3333 100 : 'Hundred' , // One Hundred, Two Hundred
3434
35- 1_000 : 'Thousand' , // Four Thousand
36-
35+ 1_000 : 'Thousand' , // One Thousand
3736 1_000_000 : 'Million' , // One Million
38-
3937 1_000_000_000 : 'Billion' , // One Billion
4038} ;
4139
4240const keys = [
43- // 1_000_000_000,
44- // 1_000_000,
45- // 1_000,
46- // 100,
47- 10 ,
41+ 1_000_000_000 ,
42+ 1_000_000 ,
43+ 1_000 ,
44+ 100 ,
4845] ;
4946
5047/**
51- * @param {number } num
52- * @return {string }
48+ * Convert a positive integer into its English representation.
49+ *
50+ * @param {number } num - The positive integer. Should be <= 2^31 - 1
51+ * @return {string } - The English words for the given number
52+ *
5353 * @pomodoro II
5454 */
5555function numberToWords ( num ) {
56- if ( num < 21 ) return map [ num ] ;
56+ if ( map [ num ] && num < 99 ) return map [ num ] ;
5757
5858 let ans = [ ] ;
59- // let i = 0;
60-
61- // while (num && i < keys.length) {
62- // // const div = keys[i++]; // 10
63- // const div = 10;
64- // const reminder = num % div; // 1
65- // const left = num - reminder; // 20
66-
67- // if (left && map[left] !== undefined) {
68- // ans.push(map[left]);
69- // num -= left;
70- // }
71-
72- // num = reminder;
73- // }
74- ans = ans . concat ( numberToWords ( Math . floor ( num / 10 ) * 10 ) ) ;
75- ans = ans . concat ( numberToWords ( Math . floor ( num % 10 ) ) )
59+ let i = 0 ;
60+
61+ while ( num && i < keys . length ) {
62+ const div = keys [ i ++ ] ;
63+ if ( Math . floor ( num / div ) ) {
64+ ans = ans . concat ( numberToWords ( Math . floor ( num / div ) ) ) ;
65+ ans = ans . concat ( map [ div ] ) ;
66+ num %= div ;
67+ }
68+ }
69+
70+ if ( num ) {
71+ ans = ans . concat ( numberToWords ( Math . floor ( num / 10 ) * 10 ) ) ;
72+ ans = ans . concat ( numberToWords ( Math . floor ( num % 10 ) ) ) ;
73+ }
7674
7775 return ans . join ( ' ' ) ;
7876} ;
7977
80- // convert a number into its English representation
81-
82- // 21
83- // Twenty One
84-
85- // 1_234_567_891
86-
87- console . log ( process . version ) ;
88-
8978module . exports = numberToWords ;
0 commit comments