Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get different digits starting from the most significant digit in a number in c?

Tags:

c

I am solving a problem in which a positive integer is given and i have to display it in words.

For example if a number is 2134 the output should be "two one three four" . If i use the modulus operator and use the recursion technique, i get the digits starting from the least significant digit i.e "four three one two"

I can also reverse the number and then use modulus operator but i am looking for a better method.

What can be a better approach of solving this problem?.What concept am i missing?

like image 308
poorvank Avatar asked Jun 06 '13 16:06

poorvank


2 Answers

My simple answer:

void printNum(int x)
{
    static const char * const num[] = {
        "zero ", "one ", "two "  , "three ", "four ",
        "five ", "six ", "seven ", "eight ", "nine "
    };

    if (x < 10) {
        printf(num[x]);
        return;
    }
    printNum(x / 10);
    printNum(x % 10);
}

edit

After some more experimenting and tweaking, I came up with this version. I think this is the about the most "pure" recursive function I can make.

void printNum(int x)
{
    static const char * const num[] = {"zero ",  "one ", "two ", "three ",
                                       "four ",  "five ", "six ", "seven ",
                                       "eight ", "nine "};
    (x < 10)? printf(num[x]) : (printNum(x / 10), printNum(x % 10));
}
like image 172
abelenky Avatar answered Sep 17 '22 19:09

abelenky


In case you're looking for recursive solution:

void num2word(int n) {
    if (n / 10 == 0) {
        // print the word for n
    }
    else {
        num2word(n / 10);
        // print the word for n % 10
    }
}
like image 28
Ye Liu Avatar answered Sep 19 '22 19:09

Ye Liu