Dourbt n leetcode problem

class Solution {
public:
vector countBits(int num) {
vector res(num + 1);

    for(int i = 1; i < num + 1; i++) {
        if(i % 2 == 0) {
            res[i] = res[i >> 1];                
        }else{
            res[i] = res[i >> 1] + 1;
        }
    }
    
    return res;
}

};

In this problem,https://leetcode.com/problems/counting-bits/
if we are taking the num =5,if the coounting is taken from 1 then its accepted its giving a wrong ans for the count from 0 to 4 ,but if we dont take the cout from 0 then how we will get the 0 in the output list.Please explain me this I am getting confused

hello @Somasree

why u stopped at 4 only ? here to get the count of bits in 5, u need to iterate till 5 na?

for 0 answer is already 0 , by default vector will have 0 value thats why no need to take care of 0 explicitly

Why we need to take 2 seperate cases for i=odd an di=even,because in this approach we are printing the decimal value of the binary

…

we checking where the last bit (rightmost)is set or not.
for odd number , right most bit will be set. thats why if num is odd we are adding additional 1

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.