Convert a number into a string of words

    by nikoo28

    Question: Given an integer N, convert it into a string of words.


    Input: N = 345
    Output: three hundred forty five

    This is one of the most common problems that we come across in out daily lives. We need to input a number from the user and print it in words.

    First, we perform a number of checks on the input string. If it is in any way invalid, the result is the empty string (“”).

    Next, we take note of whether or not the string begins with a ‘-‘. If it does we remove it.

    If what is left is composed entirely of zeros, we just return “zero”.
    The number can then be processed taking each digit at a time and evaluating it.
    I have added comments in the code for a better understanding of the algorithm.

    /* Program to print a given number in words. The program handles
       numbers from 0 to 9999 */
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <iostream>
    
    using namespace std;
    
    /* A function that prints given number in words */
    void convert_to_words(char *num)
    {
        int len = strlen(num);  // Get number of digits in given number
    
        /* Base cases */
        if (len == 0) {
            fprintf(stderr, "empty string\n");
            return;
        }
        if (len > 4) {
            fprintf(stderr, "Length more than 4 is not supported\n");
            return;
        }
    
        /* The first string is not used, it is to make array indexing simple */
        string single_digits[] = { "zero", "one", "two", "three", "four",
                                  "five", "six", "seven", "eight", "nine"};
    
        /* The first string is not used, it is to make array indexing simple */
        string two_digits[] = {"", "ten", "eleven", "twelve", "thirteen", "fourteen",
                         "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    
        /* The first two string are not used, they are to make array indexing simple*/
        string tens_multiple[] = {"", "", "twenty", "thirty", "forty", "fifty",
                                 "sixty", "seventy", "eighty", "ninety"};
    
        string tens_power[] = {"hundred", "thousand"};
    
        /* Used for debugging purpose only */
        printf("\n%s: ", num);
    
        /* For single digit number */
        if (len == 1) {
            cout << single_digits[*num - '0'] << " ";
            return;
        }
    
         /* Iterate while num is not '\0' */
         while (*num != '\0') {
    
            /* Code path for first 2 digits */
            if (len >= 3) {
                if (*num -'0' != 0) {
                    cout << single_digits[*num - '0'] << " ";
                    cout << tens_power[len-3] << " "; // here len can be 3 or 4
                }
                --len;
            }
    
            /* Code path for last 2 digits */
            else {
                /* Need to explicitly handle 10-19. Sum of the two digits is
                   used as index of "two_digits" array of strings */
                if (*num == '1') {
                    int sum = *num - '0' + *(num + 1)- '0';
                    cout << two_digits[sum] << " ";
                    return;
                }
    
                /* Need to explicitely handle 20 */
                else if (*num == '2' && *(num + 1) == '0') {
                    cout << "twenty ";
                    return;
                }
    
                /* Rest of the two digit numbers i.e., 21 to 99 */
                else {
                    int i = *num - '0';
                    cout << (i? tens_multiple[i]: "") << " ";
                    ++num;
                    if (*num != '0')
                        cout << single_digits[*num - '0'] << " ";
                }
            }
            ++num;
        }
    }
    
    /* Driver program to test above function */
    int main(void)
    {
        cout << "Enter a number to convert to words:- ";
    
        char num[10];
    
        cin >> num;
        convert_to_words(num);
    
        cout << endl;
    
        return 0;
    }
    Code language: C++ (cpp)

    Here is the running link of the code:- http://ideone.com/p6aUvz

    5 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • MiscStrings

    Common String Algorithms

    by nikoo28
    2 minutes read

    In this post, I would try to implement the following string-related algorithm questions. I would like to implement these using Java and try to make additional comments which I think that are useful for understanding the implementations of some type of data structures in Java programming language. Non Repeated Characters in String : Return the unique characters in a given letter. Anagram Strings : Given two strings, check if they’re anagrams or not. Two strings are anagrams if they are written using the same exact letters, ignoring space, punctuation and…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Find the first N prime numbers. (Method 3)

    by nikoo28
    3 minutes read

    Question: Given an integer N, find the prime numbers in that range from 1 to N. Input: N = 25Output: 2, 3, 5, 7, 11, 13, 17, 19, 23 We discussed the basic approaches to find the first N prime numbers in these posts Find the first N prime numbers (Method 1) Find the first N prime numbers (Method 2) It is advised that you go through the above posts to get a basic understanding of the approach that we have used to determine the prime numbers. Now lets analyze…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Find the first N prime numbers. (Method 2)

    by nikoo28
    2 minutes read

    Question: Given an integer N, find the prime numbers in that range from 1 to N. Input: N = 25 Output: 2, 3, 5, 7, 11, 13, 17, 19, 23 We discussed the most basic approach to find the first N prime numbers in this post. Find the first N prime numbers. (Method 1) Please go through the post if you are not familiar with the naive methods. They are necessary to learn how the code can be optimized further. So let us try to further optimize the previously discussed…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Find the first N prime numbers. (Method 1)

    by nikoo28
    2 minutes read

    Question: Given an integer N, find the prime numbers in that range from 1 to N. Input: N = 25 Output: 2, 3, 5, 7, 11, 13, 17, 19, 23 Today let us discuss about a very common but very interesting problem “To find prime numbers in first N Natural numbers “. I will be taking here a very specific approach of first giving definition of prime numbers , using that definition to derive the algorithm, and then using different properties or results that can be further applied to our…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Determine if 2 rectangles overlap

    by nikoo28
    2 minutes read

    Question: You are given two axis-aligned rectangles. You have to determine if these rectangles overlap each other or not. Rectangle 1 : P1 (x, y), P2 (x,y) Rectangle 2 : P3 (x,y), P4 (x,y) In this problem statement, we are given co-ordinates for 2 rectangles and we have to determine if they overlap or not. In a way we can say that our use case looks like this. At the first glance, the problem seems to look very complicated. If you are coming up with a complicated set of conditionals,…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Misc

    Reverse bits in an unsigned integer

    by nikoo28
    1 minutes read

    Question: Given an unsigned Integer, you need to reverse its bits. There are several methods of reversing the bits of an unsigned integer. Here, we devise an algorithm using the XOR swap trick. Hint: How do you swap the ith bit with the jth bit? Try to figure out if you could use the XOR operation to do it. The XOR swap trick: Reversing bits could be done by swapping the n/2 least significant bits with its most significant bits. The trick is to implement a function called swapBits(i, j),…

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More