Skip to content

Commit 98e5eaa

Browse files
authored
Playing With Bits Solution Added
1 parent e8b2705 commit 98e5eaa

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Hacker Blocks/Playing With Bits.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/* Hacker Blocks */
2+
/* Title - Playing With Bits */
3+
/* Created By - Akash Modak */
4+
/* Date 7/1/2020 */
5+
6+
// Prateek Bhayia likes to play with bits. One day Prateek bhayia decides to assign a task to his student Sanya. You have help Sanya to complete this task. Task is as follows - Prateek Bhayia gives Q queries each query containing two integers a and b. Your task is to count the no of set-bits in for all numbers between a and b (both inclusive)
7+
8+
// Input Format
9+
// Read Q - No of Queries, Followed by Q lines containing 2 integers a and b.
10+
11+
// Constraints
12+
// Q,a,b are integers.
13+
14+
// Output Format
15+
// Q lines, each containing an output for your query.
16+
17+
// Sample Input
18+
// 2
19+
// 1 1
20+
// 10 15
21+
// Sample Output
22+
// 1
23+
// 17
24+
25+
#include<iostream>
26+
using namespace std;
27+
int countSetBits(int n){
28+
int ans=0;
29+
while(n>0){
30+
if(n&1==1)
31+
ans++;
32+
n=n>>1;
33+
}
34+
return ans;
35+
}
36+
int main() {
37+
int q,a,b;
38+
cin>>q;
39+
while(q--){
40+
cin>>a>>b;
41+
int count =0;
42+
for(int i=a;i<=b;i++){
43+
count+= countSetBits(i);
44+
}
45+
cout<<count<<endl;
46+
}
47+
return 0;
48+
}

0 commit comments

Comments
 (0)