Wednesday, December 28, 2011

ENglish phrase of an integer number

Given an integer from 0 to 9.99,999, print an English phrase that describes the integer.

1 comment:

  1. #include < math.h >

    /* Convert a given number in to English phrase */
    char word1[][20] = { "",
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
    "Seven",
    "Eight",
    "Nine"};
    char word11[][20] = {"",
    "Eleven",
    "Twelve",
    "Thirteen",
    "Fourteen",
    "Fifteen",
    "Sixteen",
    "Seventeen",
    "Eighteen",
    "Nineteen"
    };
    char word10[][20] = {"",
    "Ten",
    "Twenty",
    "Thirty",
    "Forty",
    "Fifty",
    "Sixty",
    "Seventy",
    "Eighty",
    "Ninety"
    };
    char word100[][30] = {"",
    "Hundred",
    "Thousand",
    "lakhs"
    };
    char msg[500];


    void Convert(int num)
    {
    int len = 1, tmp;

    // Calculate the length of the number
    while(pow(10, (double)len) <= num)
    len++;

    printf("len: %d\n", len);

    // parse the number from left
    if(num == 0)
    {
    printf("zero\n");
    }
    else
    {
    if(len > 3)
    {
    if(len > 3 && len % 2 == 0)
    len++;
    do
    {
    if(len > 3)
    {
    tmp = num/(int)pow(10, (double)len-2);
    if(tmp/10 == 1 && tmp % 10 != 0)
    {
    sprintf(msg + strlen(msg)," %s ", word11[tmp%10]);
    }
    else
    {
    sprintf(msg + strlen(msg), "%s ", word10[tmp/10]);
    sprintf(msg + strlen(msg), " %s ", word1[tmp%10]);
    }
    sprintf(msg + strlen(msg)," %s ", word100[len/2]);
    num = num % (int)pow(10, (double)len - 2);
    len = len - 2;
    printf("len : %d num : %d\n", len, num);
    }
    else
    {
    tmp = num/100;
    if(tmp != 0)
    {
    sprintf(msg + strlen(msg)," %s ", word1[tmp]);
    sprintf(msg + strlen(msg)," %s ", word100[len/2]);
    }
    tmp = num % 100;
    if(tmp/10 == 1 && tmp %10 != 0)
    {
    sprintf(msg + strlen(msg)," %s ", word11[tmp%10]);
    }
    else
    {
    sprintf(msg + strlen(msg)," %s ", word10[tmp/10]);
    sprintf(msg + strlen(msg)," %s ", word1[tmp%10]);
    }
    len = 0;
    }
    }while(len > 0 && (num != 0));
    }
    }
    printf("MSG: %s\n", msg);
    }

    int main()
    {
    int num;
    num = 999999;
    Convert(num);
    return 0;
    }

    ReplyDelete