All it does is start from right to left, grabbing every 3 digits and pushing them into a chunks
array.
We then adjust for the scale we're at, and make sure we have enough digits to justify that scale.
Now, here's the key. For each chunk, we process it in this manner:
- Split it into individual integers ("123" becomes [1, 2, 3])
- Add tens word if array item exists
- Add 'and' string after units or tens integer (optional)
- Add hundreds word if array item exists

Complexity of Final Solution
Let n
be the number of digits in the input num
. We iterate through the string equivalent of num
, and examining 3 digits at a time for O(n)
linear time complexity. When converting nums
to a string of length n
, we have O(n)
space complexity.
xxxxxxxxxx
18
var assert = require('assert');
function numberToWords(n) {
// convert n to words
return n;
}
try {
assert.equal(numberToWords(1234), 'one thousand two hundred and thirty four');
console.log(
'PASSED: ' +
"assert.equal(numberToWords(1234), 'one thousand two hundred and thirty four');"
);
} catch (err) {
console.log(err);
}
OUTPUT
Results will appear here.