Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What am I missing in this recursion?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading