No output is comping

playing with bits

hi @Chetan_Khandelwal
you are not supposed to modify the i pointer (it is a iterator)
everytime you are supposed to count the bits of numbers lying in the range
for(int i=a;i<=b;i++){
int c=i; //modification
while(c>0){

            count=count+(c&1);
            c=c>>1;
        }
    }

Hello @Chetan_Khandelwal,

@AASTHA011 has pointed out the correct mistake in your code.
Please, read her post carefully.

What she is trying to say:
If you would perform the bitwise AND and right shift operator directly on i, then it will change the value of i.
As the iteration of your loop depends upon the i.
Thus, modifying it would affect the number of iteration.

Now, adding to what she has explained.
This code would work perfectly for small values of a and b.
But, will cause TLE for large value.

Solution:
You have to use a more efficient approach to solve the above problem:
This approach is named as Brian Kernighan’s Algorithm

In this approach, we will use Bit operator for counting bit set in number.
Instead of scanning all the bits of a number, we will only look at set bits in this approach.

When we do bitwise AND between (number) & (number-1), Right most SET bit of “number” will be unset.
image

For better understanding, see the following code:

Hope, this would help.
Give a like, if you are satisfied.

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.