Program to convert a given number to words | A function that prints given number in words ; Get number of digits in given number ; Base cases ; The first string is not used , it is to make array indexing simple ; The first string is not used , it is to make array indexing simple ; The first two string are not used , they are to make array indexing simple ; Used for debugging purpose only ; For single digit number ; Iterate while num is not '\0 ; Code path for first 2 digits ; here len can be 3 or 4 ; Code path for last 2 digits ; Need to explicitly handle 10 - 19. Sum of the two digits is used as index of " two _ digits " array of strings ; Need to explicitely handle 20 ; Rest of the two digit numbers i . e . , 21 to 99
def convert_to_words ( num ) : NEW_LINE INDENT l = len ( num ) NEW_LINE if ( l == 0 ) : NEW_LINE INDENT print ( " empty ▁ string " ) NEW_LINE return NEW_LINE DEDENT if ( l > 4 ) : NEW_LINE INDENT print ( " Length ▁ more ▁ than ▁ 4 ▁ is ▁ not ▁ supported " ) NEW_LINE return NEW_LINE DEDENT single_digits = [ " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " ] NEW_LINE two_digits = [ " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " ] NEW_LINE tens_multiple = [ " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " ] NEW_LINE tens_power = [ " hundred " , " thousand " ] NEW_LINE print ( num , " : " , end = " ▁ " ) NEW_LINE if ( l == 1 ) : NEW_LINE INDENT print ( single_digits [ ord ( num [ 0 ] ) - 48 ] ) NEW_LINE return NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT x = 0 NEW_LINE while ( x < len ( num ) ) : NEW_LINE INDENT if ( l >= 3 ) : NEW_LINE INDENT if ( ord ( num [ x ] ) - 48 != 0 ) : NEW_LINE INDENT print ( single_digits [ ord ( num [ x ] ) - 48 ] , end = " ▁ " ) NEW_LINE print ( tens_power [ l - 3 ] , end = " ▁ " ) NEW_LINE DEDENT l -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( ord ( num [ x ] ) - 48 == 1 ) : NEW_LINE INDENT sum = ( ord ( num [ x ] ) - 48 + ord ( num [ x + 1 ] ) - 48 ) NEW_LINE print ( two_digits [ sum ] ) NEW_LINE return NEW_LINE DEDENT elif ( ord ( num [ x ] ) - 48 == 2 and ord ( num [ x + 1 ] ) - 48 == 0 ) : NEW_LINE INDENT print ( " twenty " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT i = ord ( num [ x ] ) - 48 NEW_LINE if ( i > 0 ) : NEW_LINE INDENT print ( tens_multiple [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " " , end = " " ) NEW_LINE DEDENT x += 1 NEW_LINE if ( ord ( num [ x ] ) - 48 != 0 ) : NEW_LINE INDENT print ( single_digits [ ord ( num [ x ] ) - 48 ] ) NEW_LINE DEDENT DEDENT DEDENT x += 1 NEW_LINE DEDENT DEDENT