Print all numbers up to N in words in lexicographical order | Java program for the above approach ; 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
import java . util . * ; class GFG { static String convert_to_words ( int n ) { char num [ ] = String . valueOf ( n ) . toCharArray ( ) ; int len = num . length ; String ans = " " ; if ( len == 0 ) { ans += " Empty ▁ String " ; return ans ; } String [ ] single_digits = new String [ ] { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; String [ ] two_digits = new String [ ] { " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " } ; String [ ] tens_multiple = new String [ ] { " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " } ; String [ ] tens_power = new String [ ] { " hundred " , " thousand " } ; if ( len == 1 ) { ans += single_digits [ num [ 0 ] - '0' ] ; return ans ; } int x = 0 ; while ( x < num . length ) { if ( len >= 3 ) { if ( num [ x ] - '0' != 0 ) { ans += single_digits [ num [ x ] - '0' ] ; ans += " ▁ " ; ans += tens_power [ len - 3 ] ; ans += " ▁ " ; } -- len ; } else { if ( num [ x ] - '0' == 1 ) { int sum = num [ x ] - '0' + num [ x ] - '0' ; ans += two_digits [ sum ] ; return ans ; } else if ( num [ x ] - '0' == 2 && num [ x + 1 ] - '0' == 0 ) { ans += " twenty " ; return ans ; } else { int i = ( num [ x ] - '0' ) ; if ( i > 0 ) { ans += tens_multiple [ i ] ; ans += " ▁ " ; } else ans += " " ; ++ x ; if ( num [ x ] - '0' != 0 ) ans += single_digits [ num [ x ] - '0' ] ; } } ++ x ; } return " " ; } static void lexNumbers ( int n ) { Vector < String > s = new Vector < String > ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { s . add ( convert_to_words ( i ) ) ; } Collections . sort ( s ) ; Vector < String > ans = new Vector < String > ( ) ; for ( int i = 0 ; i < n ; i ++ ) ans . add ( s . get ( i ) ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) System . out . print ( ans . get ( i ) + " , ▁ " ) ; System . out . print ( ans . get ( n - 1 ) ) ; } public static void main ( String [ ] args ) { int n = 5 ; lexNumbers ( n ) ; } }