We can use AND operation for this purpose, we can just AND the number with 1 and get the value and keep on adding with the count until the value n becomes 0.
int count(int n){
int count = 0;
while(n>0){
count += (n&1);
n = n >> 1;
}
}
Thus the above subroutine will simply increase the count and make the n to be shift right so as to remove last significant bit.
That was a nice question to answer
Friend, If you have any doubts in understanding do let me know in
the comment section. I will be happy to help you further.
Thanks
Get Answers For Free
Most questions answered within 1 hours.