简体   繁体   中英

return value meaning | pattern

What does the following function return? (in terms of meaning)

int f(int n){
    if(n == 0) return 0;
    else return n % 2 + f(n / 2)
}

Tried running the code, but couldn't find any pattern in the results

This output of this function can be interpreted as the number of 1s (in base 10) when the number n is represented in binary.

The base case is when n == 0 , where the number of 1s is 0 .

For every other n , there is a recursive call. There are two parts to this. The first, which is n % 2 , finds out the last bit of n . If it is a 1 , it contributes to the value returned, and is hence, counted. The second part, f(n/2) , is computing the number of 1s in all the bits of n except the last bit. This is because n/2 is n with a one bit right shift.

To put it together, the function works as follows. It checks the last bit, and if 1 , it adds it to the total. It then performs a recursive call on itself with the last bit removed. This goes on till all bits are removed, which is covered by the base case.

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