Issue
So I am trying to recursive print all the sum of odd digits in a number. Like the number 12345 would be 9 This code does not work, but I do not understand why.
public static int oddSum(int n){
String nn = Integer.toString(n);
if(nn.length()==1 && Integer.parseInt(nn)%2==1) {
return Integer.parseInt(nn);
} else if(nn.length()==1 && Integer.parseInt(nn)%2==0) {
return 0;
}
if((int)nn.charAt(0)%2 == 1) {
return oddSum(Integer.parseInt(nn.substring(1))+(int)nn.charAt(0));
} else {
return oddSum(Integer.parseInt(nn.substring(1)));
}
}
Solution
I kinda feel like this is a homework problem, but I'll bite.
I don't specifically know java, so I can't comment on the details of the code. But, if I'm reading it correctly, it seems like you're taking an integer, converting it to a string, stripping characters and returning them to integers to process? That seems convoluted.
What about this pseudo-code?
int oddSum(n)
{
if (n < 10)
{
if (n%2 == 1)
return n
else
return 0
}
return oddSum(n/10) + oddSum(n%10)
}
Answered By - Weylin Piegorsch
Answer Checked By - Cary Denson (JavaFixing Admin)