简体   繁体   中英

how can i count digits of a number using recursion?

yes i know other ways to count digits and returning to main function from the recursion function, but i'd like to print it in the void function.im having difficulty with it. could somebody help?

#include <iostream>
using namespace std;
void recursive_function(int num)
{
    int sum=0;
    while(num!=0){
        recursive_function(num/10);
        sum++;
    }
    cout<<sum<<endl;
}
int main()
{
    recursive_function(345289467);
    return 0;
}

If you do not want to use the return-stack to count your digits, you will need to pass the current count throughout the call stack as function parameter:

void recursive_function(int num, int count=1)
{
    if (num>=10) {
       recursive_function(num/10, count+1);
    } else {
       cout<<count<<endl;
    }
}

your recursive function should return integer.

#include <iostream>
using namespace std;
int recursive_function(int num)
{    

    if(num>9){
        return 1+recursive_function(num/10);        
    }else
    return 1;
}
int main()
{
    cout << recursive_function(123456789);
    return 0;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM