One Pager Cheat Sheet
- You can convert a number to its text equivalent using
number spellinginO(n)time andO(n)space complexity, where n is the number of digits and the number of digits must not exceed100. - We can
convertthenumber123 to astring typeto start our operation. - We need to define
units,tensandscalesfor building the final string, and then divide the number into chunks of 3 digits to account for different scales. - We
iteratethroughnuminO(n)lineartime, andconvertit to astringoflength nforO(n)spacecomplexity.
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.
xxxxxxxxxx168
}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
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.


