简体   繁体   中英

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

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 ie:

if (n > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM