Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack overflow for recursive count of elements in java

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)."

like image 437
AntBite Avatar asked Jan 11 '13 23:01

AntBite


People also ask

Can recursion cause stack overflow?

The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.

How does stack overflow solve recursion?

In order to prevent stack overflow bugs, you must have a base case where the function stops make new recursive calls. If there is no base case then the function calls will never stop and eventually a stack overflow will occur. Here is an example of a recursive function with a base case.

How do you use recursion to count?

To use recursion to add integers from first to last: The sum of the last integer on the list is itself: last. The sum of all the integers is the first integer added to the sum of the remaining integers.

Can stack be used for recursion?

Recursive functions use something called “the call stack.” When a program calls a function, that function goes on top of the call stack. This is similar to a stack of books. You add things one at a time.


1 Answers

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)

like image 81
Ivaylo Strandjev Avatar answered Sep 28 '22 02:09

Ivaylo Strandjev