
Given ‘N’ = 4,
Its binary representation is 0..0100, therefore there is only 1 set bit, hence the answer will be 1.
The first line of input contains ‘T’, denoting the number of test cases. Then each test case follows.
Each test case contains a single integer ‘N’, denoting the number given.
For each test case, print a single line that contains a single integer that denotes the total number of 1s which satisfy the above description.
You are not required to print the expected output; it has already been taken care of. Just implement the function.
1 <= T <= 100
1 <= N <= 10 ^ 18
Time Limit: 1 sec.
The idea is to check every bit in the number and maintain a counter and increase it by 1 if the bit is set.
The steps are as follows:
The idea here is subtracting 1 from a decimal number flips all the bits after the rightmost set bit(which is 1) including the rightmost set bit. So if we subtract a number by 1 and do it bitwise & with itself (‘N’ & (‘N’ - 1)), we unset the rightmost set bit. If we do ‘N’ & (‘N’ - 1) in a loop and count the number of times the loop executes, we get the set bit count.
The steps are as follows: