-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtotalSetBits.cpp
59 lines (48 loc) Β· 1.03 KB
/
totalSetBits.cpp
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
https://www.geeksforgeeks.org/problems/count-total-set-bits-1587115620/1
// good question :- TLE
//{ Driver Code Starts
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution{
private:
int setBits(int n) {
int count = 0;
while (n > 0) {
if (n % 2 == 1) {
count++;
}
n = n / 2;
}
return count;
}
public:
// n: input to count the number of set bits
//Function to return sum of count of set bits in the integers from 1 to n.
int countSetBits(int N)
{
int totalBits = 0;
for (int i = 0; i <= N; i++) {
totalBits += setBits(i);
}
return totalBits;
}
};
//{ Driver Code Starts.
// Driver code
int main()
{
int t;
cin>>t;// input testcases
while(t--) //while testcases exist
{
int n;
cin>>n; //input n
Solution ob;
cout << ob.countSetBits(n) << endl;// print the answer
}
return 0;
}
// } Driver Code Ends