Print all numbers up to N in words in lexicographical order | Function to convert a number to words ; Stores the digits ; Base cases ; Stores strings of unit place ; Stores strings for corner cases ; Stores strings for ten 's place digits ; Stores strings for powers of 10 ; If given number contains a single digit ; Iterate over all the digits ; Represent first 2 digits in words ; Represent last 2 digits in words ; Explicitly handle corner cases [ 10 , 19 ] ; Explicitly handle corner case 20 ; For rest of the two digit numbers i . e . , 21 to 99 ; Function to print all the numbers up to n in lexicographical order ; Convert all numbers in words ; Sort all strings ; Print answer ; Driver Code
function convert_to_words ( n ) { let num = ( n ) . toString ( ) . split ( " " ) ; let len = num . length ; let ans = " " ; if ( len == 0 ) { ans += " " ; return ans ; } let single_digits = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; let two_digits = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; let tens_multiple = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; let tens_power = [ " " , " " ] ; if ( len == 1 ) { ans += single_digits [ num [ 0 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ; return ans ; } let x = 0 ; while ( x < num . length ) { if ( len >= 3 ) { if ( num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) != 0 ) { ans += single_digits [ num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ; ans += " " ; ans += tens_power [ len - 3 ] ; ans += " " ; } -- len ; } else { if ( num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) == 1 ) { let sum = num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) + num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; ans += two_digits [ sum ] ; return ans ; } else if ( num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) == 2 && num [ x + 1 ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) == 0 ) { ans += " " ; return ans ; } else { let i = ( num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; if ( i > 0 ) { ans += tens_multiple [ i ] ; ans += " " ; } else ans += " " ; ++ x ; if ( num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) != 0 ) ans += single_digits [ num [ x ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ; } } ++ x ; } return " " ; } function lexNumbers ( n ) { let s = [ ] ; for ( let i = 1 ; i <= n ; i ++ ) { s . push ( convert_to_words ( i ) ) ; } s . sort ( ) let ans = [ ] ; for ( let i = 0 ; i < n ; i ++ ) ans . push ( s [ i ] ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) document . write ( ans [ i ] + " " ) ; document . write ( ans [ n - 1 ] ) ; } let n = 5 ; lexNumbers ( n ) ;