#include
using namespace std;
int main() {
int t;
cin>>t;
while(t–){
int a,b;
int count= 0;
cin>>a>>b;
for(int i = a; i <= b; i++){
while(i>0){
if((i&1)>0){
count++;
i>>1;
}
else{
i>>1;
}
}
}
cout<<count;
}
return 0;
}
Why I am not getting any output
Mistake:
in your code while iterating from [a,b] ==> you are directly change the current ith number…without storing it in some other variable ===> which unfortunately make changes in our iterator i… which you are considering a current ith number ===> so what you need to do is==> you need to first store the current ith number in another variable and than proceed with the calculation of no. of set bits in the variable…
your Code:
for(int i = a; i <= b; i++){
while(i>0){
if((i&1)>0){
count++;
i>>1;
}
else{
i>>1;
}
}
}
Correct is:
for(int i = a; i <= b; i++){
int number = i;
while(number>0){
if((number&1)!=0){
count+=1;
number = number>>1;
}
else{
number = number>>1;
}
}
}
Complete code is:
I hope this helps But if you have further doubt feel free to ask