Given a number ‘N’, you are supposed to calculate the number of 1s in the binary representation of the given number.
For example:
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.
Output Format :
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.
Note:
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.
2
4
3
1
2
For the first test case :
The binary representation 4 is 0..0100, therefore there is only 1 set bit. Hence, the answer will be 1.
For the Second Test case:
The binary representation 3 is 0..0011, therefore there are 2 set bits. Hence, the answer will be 2.
2
16
15
1
4
Can you check every bit of the given number?
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:
O(log(N)), where ‘N’ is the number given.
Since the max number of bits, a number can have is log(N). Hence, the overall time complexity will be O(log(N)).
O(1).
Since we are not using any extra space. Hence, the overall space complexity is O(1).