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 ie "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?
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));
}
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
}
}
Going for a pure math answer, because I think that's what you're 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 running it produces:
two nine eight seven six one two three four five
It should work with any size number that a long long can handle (in other languages, or with a big number library in C, it can handle something arbitrarily large).
Now... I'm not sure the use of log10 and pow is the fastest. But it's the most fun :-)
If it is a null terminated char *, then why not just do this:
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);
1234 / 1000 => 1
1234 % 1000 => 234 234 / 100 => 2
1234 % 100 => 34 34 / 10 => 3
1234 % 10 => 4
You can pretty easely build a loop around that, but you may go even easer with itoa, sprintf, and std::to_string .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.