Print all numbers up to N in words in lexicographical order | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string convert_to_words ( int n ) { char num [ 1000 ] ; string str = to_string ( n ) ; strcpy ( num , str . c_str ( ) ) ; char * arr_ptr = & num [ 0 ] ; int len = strlen ( arr_ptr ) ; string ans = " " ; if ( len == 0 ) { ans += " Empty ▁ String " ; return ans ; } string single_digits [ ] = { " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " } ; string two_digits [ ] = { " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " } ; string tens_multiple [ ] = { " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " } ; string tens_power [ ] = { " hundred " , " thousand " } ; if ( len == 1 ) { ans += single_digits [ num [ 0 ] - '0' ] ; return ans ; } int x = 0 ; while ( x < len ) { 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 ; for ( int i = 1 ; i <= n ; i ++ ) { s . push_back ( convert_to_words ( i ) ) ; } sort ( s . begin ( ) , s . end ( ) ) ; vector < string > ans ; for ( int i = 0 ; i < n ; i ++ ) ans . push_back ( s [ i ] ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) cout << ans [ i ] << " , ▁ " ; cout << ans [ n - 1 ] ; } int main ( ) { int n = 5 ; lexNumbers ( n ) ; return 0 ; }