Skip to content

Commit 21a4884

Browse files
committed
count set bit from 1 to N
1 parent 134985e commit 21a4884

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
/*
3+
You are given a number N. Find the total count of set bits for all numbers from 1 to N(both inclusive).
4+
5+
Example 1:
6+
7+
Input: N = 4
8+
Output: 5
9+
Explanation:
10+
For numbers from 1 to 4.
11+
For 1: 0 0 1 = 1 set bits
12+
For 2: 0 1 0 = 1 set bits
13+
For 3: 0 1 1 = 2 set bits
14+
For 4: 1 0 0 = 1 set bits
15+
Therefore, the total set bits is 5.*/
16+
17+
#include<bits/stdc++.h>
18+
using namespace std;
19+
20+
// Function to count set bits in the given number x
21+
// n: input to count the number of set bits
22+
int largestpowerof2inrange(int n)
23+
{
24+
int x=0;
25+
while((1<<x) <=n)
26+
{
27+
x++;
28+
}
29+
return x-1;
30+
}
31+
int countSetBits(int n)
32+
{
33+
// Your logic
34+
if(n==0) return 0;
35+
int x=largestpowerof2inrange(n);
36+
int first= x*(1<<(x-1));
37+
int second= n-(1<<x)+1;
38+
int third=n-(1<<x);
39+
int ans=first+second+countSetBits(third);
40+
return ans;
41+
}
42+
43+
// Driver code
44+
int main()
45+
{
46+
int t;
47+
cin>>t;// input testcases
48+
while(t--) //while testcases exist
49+
{
50+
int n;
51+
cin>>n; //input n
52+
53+
cout << countSetBits(n) << endl;// print the answer
54+
}
55+
return 0;
56+
}
57+
// } Driver Code Ends

0 commit comments

Comments
 (0)