How to get different numbers, starting with the most significant digit in the number in c?

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

For example, if the number is 2134 , the output should be "two one three four" . If I use the module operator and use the recursion method, I get digits starting with the least significant digit ie "four three one two"

I can also cancel the number and then use the module operator, but I'm looking for a better method.

What could be the best approach to solving this problem? What concept am I missing?

+4
source share
5 answers

My simple answer is:

 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); } 

change

After several experiments and adjustments, I came up with this version. I think this is about the most β€œpure” recursive function that I can do.

 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)); } 
+4
source

If you are looking for a 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 } } 
+2
source

We go through a clean mathematical answer, because I think you are looking for:

 #include <math.h> #include <stdio.h> main() { long long mynum = 2987612345; long long firstDigitValue; int firstDigit; char *names[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; while (mynum > 0) { firstDigit = (int) (mynum/pow(10,(int)log10(mynum))); firstDigitValue = firstDigit * pow(10,(int)log10(mynum)); mynum -= firstDigitValue; printf("%s ", names[firstDigit]); } printf("\n"); } 

And then its launch causes:

 two nine eight seven six one two three four five 

It should work with any size number that can process for a long time (in other languages ​​or with a large library of numbers in C, it can handle something arbitrarily large).

Now ... I'm not sure that using log10 and pow is the fastest. But this is the most interesting :-)

+2
source

If this is the empty end of char *, then why not just do it:

 int i = 0; while(char[i] != null){ switch(char[i]): case '1': printf("One "); break; .... i++; } 

if its not a char *, turn it into one with char * temp = itoa (number);

+1
source
 1234 / 1000 => 1 1234 % 1000 => 234 234 / 100 => 2 1234 % 100 => 34 34 / 10 => 3 1234 % 10 => 4 

You can pretty easily create a loop around this, but you can go even easier with itoa, sprintf and std :: to_string .

+1
source

Source: https://habr.com/ru/post/1484867/


All Articles