@@ -32,58 +32,47 @@ const map = {
32
32
90 : 'Ninety' ,
33
33
100 : 'Hundred' , // One Hundred, Two Hundred
34
34
35
- 1_000 : 'Thousand' , // Four Thousand
36
-
35
+ 1_000 : 'Thousand' , // One Thousand
37
36
1_000_000 : 'Million' , // One Million
38
-
39
37
1_000_000_000 : 'Billion' , // One Billion
40
38
} ;
41
39
42
40
const 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 ,
48
45
] ;
49
46
50
47
/**
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
+ *
53
53
* @pomodoro II
54
54
*/
55
55
function numberToWords ( num ) {
56
- if ( num < 21 ) return map [ num ] ;
56
+ if ( map [ num ] && num < 99 ) return map [ num ] ;
57
57
58
58
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
+ }
76
74
77
75
return ans . join ( ' ' ) ;
78
76
} ;
79
77
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
-
89
78
module . exports = numberToWords ;
0 commit comments