5

I'm trying to count the number of Ones in the binary representation of an integer. I need to do this recursively. I think my logic is correct but I continue to get a stack overflow. I'm on day 2 troubleshooting. Here's my code:

    static int CountRecursive(int n) {
    int sum = 0;
    if (n >= 0) {
        if (n%2 == 1) {
            sum ++;
        } sum += CountRecursive(n/2);
    } return sum;
} 

My logic is based on this information: "The standard mechanism for converting from decimal to binary is to repeatedly divide the decimal number by 2 and, at each division, output the remainder (0 or 1)."

1
  • Note though that you have to tweak your solution even more to work for negative integers too. Commented Jan 12, 2013 at 0:14

1 Answer 1

11

Remove the equals in the if. 0 divided by 2 is still zero - you go into infinite recursion.

I mean make this one:

if (n >= 0)

strict comparison i.e:

if (n > 0)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.