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