-
Notifications
You must be signed in to change notification settings - Fork 22
/
count total set bits
62 lines (52 loc) · 964 Bytes
/
count total set bits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
You are given a number N. Find the total count of set bits for all numbers from 1 to N(both inclusive).
Input:
The first line of input contains an integer T denoting the number of test cases. T testcases follow. The first line of each test case is N.
Output:
For each testcase, in a new line, print the total count of all bits.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 103
Example:
Input:
2
4
17
Output:
5
35
Explanation:
Testcase1:
An easy way to look at it is to consider the number, n = 4:
0 0 0 = 0
0 0 1 = 1
0 1 0 = 1
0 1 1 = 2
1 0 0 = 1
Therefore , the total number of bits is 5.
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int t; cin>>t; while(t--)
{
int n;
cin>>n;
int Count=0,Sum=0;
for(int j=1;j<=n;j++)
{
int i=0;
Count=0;
while(j>=(1<<i))
{
int num=j|(1<<i);
if(num==j)
Count++;
i++;
}
Sum=Sum+Count;
}
cout<<Sum<<endl;
}
return 0;
}