One Pager Cheat Sheet
- You can convert a number to its text equivalent using
number spelling
inO(n)
time andO(n)
space complexity, where n is the number of digits and the number of digits must not exceed100
. - We can
convert
thenumber
123 to astring type
to start our operation. - We need to define
units
,tens
andscales
for building the final string, and then divide the number into chunks of 3 digits to account for different scales. - We
iterate
throughnum
inO(n)
linear
time, andconvert
it to astring
oflength n
forO(n)
space
complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
168
}
var assert = require('assert');
/**
* Convert an integer to its words representation
*
* @author McShaman (http://stackoverflow.com/users/788657/mcshaman)
* @source http://stackoverflow.com/questions/14766951/convert-digits-into-words-with-javascript
*/
function numberToWords(n) {
var string = n.toString(),
units,
tens,
scales,
start,
end,
chunks,
chunksLen,
chunk,
ints,
i,
word,
words,
and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g, '');
/* Is number zero? */
if (parseInt(string) === 0) {
return 'zero';
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Alright, well done! Try another walk-through.
If you had any problems with this tutorial, check out the main forum thread here.