Reputation: 32
DRoot dRoot = new DRoot();
System.out.println("Answer from main : " + dRoot.digital_root(493193));
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
public class DRoot {
public static int digital_root(int num)
{
String temp = Integer.toString(num);
int a[] = new int[temp.length()];
int output = 0;
for(int i = 0; i < temp.length(); i++) //getting individual numbers from passed in integer
{
a[i] = Integer.parseInt(temp.substring(i, i+1));
}
for (int i = 0; i < a.length; i++) //sum of all digits in the number
{
output += a[i];
}
if(String.valueOf(output).length() != 1)
{
digital_root(output);
} else {
return output;
}
return 0;
}
}
As you can see above, I have attempted to return the single digit number through an if else statement that tests "if the value of output is not equal to 1 then return digital_root(output);
" however, this return doesn't work and instead it is returning 0 from the return below which I put there to clear return errors. Any help with this problem? thanks
Upvotes: 0
Views: 83
Reputation: 829
it's because you are making a recursive call within if condition and overriding the output variable.
For example, if you pass input 1234 to your function, during the first call the output will be 10, and as length not equal to 1 it would make a recursive call again and convert it to 1 and returns it, but you are not collecting the 1 returned by it, as the method call ended the value in output during the recursive call is lost. hence the output will be still 10 and as it already executed if it will go to the last statement and return 0
so better solution is to use a variable to collect the result
int result = 0;
if(String.valueOf(output).length() != 1)
{
result = digital_root(output);
} else {
result = output;
}
return result;
Upvotes: 0
Reputation: 643
if(String.valueOf(output).length() != 1)
{
return digital_root(output);
} else {
return output;
}
Upvotes: 0
Reputation: 603
Change this line
digital_root(output);
to
return digital_root(output);
There are other optimizations which can also be done
Upvotes: 2