Code providing wrong output for test case

#include
using namespace std;

int countBits(int n)
{

int ans=0;

while(n>0)
{
	ans=ans+(n&1);
	n=n>>1;
}
return ans;

}

int main() {

int q,res=0;
cin>>q;
while(q--)
{
	int a,b,i;
	cin>>a>>b;
	for(i=a;i<=b;i++)
	{
		res=res+countBits(i);
	}
	cout<<res<<endl;
}
return 0;

}

For the test case 10,15 the output is coming as 18 instead of 17. I dry ran the code, but couldn’t find out the mistake.

hi @pratyushnitdgp19_2c287088d77b5893
refer this code -->

#include<iostream>
using namespace std;
int main(){
	
	int t;
	cin>>t;
	
	int ans_arr[1000];
	
	for(int i=0;i<t;i++){
	
	int a,b;
	cin>>a>>b;
	
	int count = 0;
	for(int j=a;j<=b;j++){
		int num = j;
			
		while(num>0){
			int rem = num%2;
			if(rem == 1){
				count++;
			}
			num=num/2;
		}
	}
	ans_arr[i]=count;
	}
	
	for(int i=0;i<t;i++){
		cout<<ans_arr[i]<<endl;
	}
}

Sir actually I was doing this problem under Bitmasking topic, so Sir I wanted to ask if this can be done using bitwise operators.

ok… refer this–>

#include <iostream>
using namespace std;

int countSetBits(int n) {
	int res = 0;
	if (n == 1){
		return 1;
	} else {
		while (n > 0) {
		n = (n & (n - 1));
		res++;
		}
		return res;
	}
}

int main() {
	int t;
    cin>>t;
	while (t--) {
		int a, b, setBits = 0;
		cin >> a >> b;

		for (int i = a; i <= b; i++) {
			setBits += countSetBits(i);
		}

		cout << setBits <<endl;
	}
	return 0;
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.