I have solved the problem but the output is 0;
Sir please see whats wrong in my code in playing with bits problem
Please share your code
#include
using namespace std;
int countbits(int a ,int b)
{ int ans=0;
for(int i=a;i<=b;i++)
{
while(i>0)
{
ans=ans+(i&1);
i=i>>1;
}
}
return ans;
}
int main()
{
int q;
cin>>q;
int a,b;
for(int i=1;i<=q;i++)
{
cin>>a,b;
int n=countbits(a,b);
cout<<n<<endl;
}
}
Hey @gupta.ritik2002 there is a syntax error while taking input of b. Also in your count bit function inside the loop you cannot use your loop control variable for calculating the set bits, instead you need to use a copy of that variable and perform operation on that. Here is your corrected code https://ide.codingblocks.com/s/185075
If you don’t have any further doubts please mark the doubt as resolved .