Finding set bits

Could you please explain what is the logic behind the code?

(https://ide.codingblocks.com/#/s/6114)

Basically in this code, you are converting every no to its binary representation and then you will determine the no of 1’s or set bits present in the binary representation of a no. For eg, the no is 15 , the binary representation of 15 is 1111 , thus no of setbits here is 1 .
Thus you are using a logic of firstly converting no to binary representation , thts why you are using n>>1 which means you are dividing by 2 the remainder , and then you are adding its value to the ans, which is initialised to 0 .

in 15 there are 4 1’s i.e 4 set bits then why the answer is 1?

Sry, answer is 4 , i typed incorrect.

https://ide.codingblocks.com/s/137179...this is what i am doing then what is the problem

Can you plz confirm the question since the code is using primeseive…