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)."
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With