Wednesday, November 13, 2019

Digital Root using Recursion


You are given a number n. You need to find the digital root of n.
DigitalRoot of a number is the recursive sum of its digits until we get a single digit number.
Eg.DigitalRoot(191)=1+9+1=>11=>1+1=>2

int digitalRoot(int n)
{
    int sum = 0;
    if (n < 10)
        return n;
     
    sum = digitalRoot(n / 10) + n % 10;
 
    if (sum / 10 != 0)
    {
        return digitalRoot(sum);
    }
    else
    {
        return sum;
    }
}

No comments:

Post a Comment